JavaScript类/对象可以有构造函数吗?它们是如何产生的?
当前回答
使用原型:
function Box(color) // Constructor
{
this.color = color;
}
Box.prototype.getColor = function()
{
return this.color;
};
隐藏“color”(有点像私有成员变量):
function Box(col)
{
var color = col;
this.getColor = function()
{
return color;
};
}
用法:
var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue
var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green
其他回答
在我看来,你们大多数人都给出了getter和setter的例子,而不是一个构造函数,即http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)。
lunch -dan更接近,但是这个例子在jsFiddle中不起作用。
这个例子创建了一个私有构造函数,该函数只在创建对象期间运行。
var color = 'black';
function Box()
{
// private property
var color = '';
// private constructor
var __construct = function() {
alert("Object Created.");
color = 'green';
}()
// getter
this.getColor = function() {
return color;
}
// setter
this.setColor = function(data) {
color = data;
}
}
var b = new Box();
alert(b.getColor()); // should be green
b.setColor('orange');
alert(b.getColor()); // should be orange
alert(color); // should be black
如果你想要分配公共属性,那么构造函数可以这样定义:
var color = 'black';
function Box()
{
// public property
this.color = '';
// private constructor
var __construct = function(that) {
alert("Object Created.");
that.color = 'green';
}(this)
// getter
this.getColor = function() {
return this.color;
}
// setter
this.setColor = function(color) {
this.color = color;
}
}
var b = new Box();
alert(b.getColor()); // should be green
b.setColor('orange');
alert(b.getColor()); // should be orange
alert(color); // should be black
这是一个构造函数:
function MyClass() {}
当你这样做时
var myObj = new MyClass();
MyClass被执行,并返回该类的一个新对象。
使用上面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闭包做的事情,因为还没有人使用闭包。
var user = function(id) {
// private properties & methods goes here.
var someValue;
function doSomething(data) {
someValue = data;
};
// constructor goes here.
if (!id) return null;
// public properties & methods goes here.
return {
id: id,
method: function(params) {
doSomething(params);
}
};
};
欢迎对此解决方案提出意见和建议。:)
构造函数的意义是什么呢 财产吗?不知道它在哪里 可能有用,有什么想法吗?
构造函数属性的目的是提供某种方式来假装JavaScript有类。你不能做的一件事是在创建对象后更改对象的构造函数。它是复杂的。
几年前我写了一篇相当全面的文章:http://joost.zeekat.nl/constructors-considered-mildly-confusing.html