JavaScript类/对象可以有构造函数吗?它们是如何产生的?
当前回答
使用上面Nick的示例,您可以使用return语句作为对象定义中的最后一条语句为不带参数的对象创建构造函数。返回你的构造函数,如下所示,它将在你每次创建对象时运行__construct中的代码:
function Box()
{
var __construct = function() {
alert("Object Created.");
this.color = 'green';
}
this.color = '';
this.getColor = function() {
return this.color;
}
__construct();
}
var b = new Box();
其他回答
在JavaScript中调用类型定义了函数的行为:
直接调用 对象上的方法调用obj.func() 构造函数调用new func() 间接调用func.call()或func.apply()
该函数在使用new操作符调用时作为构造函数调用:
function Cat(name) {
this.name = name;
}
Cat.prototype.getName = function() {
return this.name;
}
var myCat = new Cat('Sweet'); // Cat function invoked as a constructor
JavaScript中的任何实例或原型对象都有一个属性构造函数,它引用构造函数。
Cat.prototype.constructor === Cat // => true
myCat.constructor === Cat // => true
查看这篇关于构造函数属性的文章。
使用上面Nick的示例,您可以使用return语句作为对象定义中的最后一条语句为不带参数的对象创建构造函数。返回你的构造函数,如下所示,它将在你每次创建对象时运行__construct中的代码:
function Box()
{
var __construct = function() {
alert("Object Created.");
this.color = 'green';
}
this.color = '';
this.getColor = function() {
return this.color;
}
__construct();
}
var b = new Box();
http://www.jsoops.net/对于Js中的oop非常好。提供私有、受保护、公共变量和函数,并具有继承特性。示例代码:
var ClassA = JsOops(function (pri, pro, pub)
{// pri = private, pro = protected, pub = public
pri.className = "I am A ";
this.init = function (var1)// constructor
{
pri.className += var1;
}
pub.getData = function ()
{
return "ClassA(Top=" + pro.getClassName() + ", This=" + pri.getClassName()
+ ", ID=" + pro.getClassId() + ")";
}
pri.getClassName = function () { return pri.className; }
pro.getClassName = function () { return pri.className; }
pro.getClassId = function () { return 1; }
});
var newA = new ClassA("Class");
//***Access public function
console.log(typeof (newA.getData));
// function
console.log(newA.getData());
// ClassA(Top=I am A Class, This=I am A Class, ID=1)
//***You can not access constructor, private and protected function
console.log(typeof (newA.init)); // undefined
console.log(typeof (newA.className)); // undefined
console.log(typeof (newA.pro)); // undefined
console.log(typeof (newA.getClassName)); // undefined
是的,你可以像这样在类声明中定义构造函数:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
在大多数情况下,在调用传递此信息的方法之前,必须以某种方式声明所需的属性。如果你不需要一开始就设置一个属性,你可以像这样在对象中调用一个方法。可能不是最漂亮的方法,但这仍然有效。
var objectA = {
color: '';
callColor : function(){
console.log(this.color);
}
this.callColor();
}
var newObject = new objectA();