在声明对象文字时,您不能立即运行这样的函数。你可以做什么:
var car = {
init : function(wheels,color,speed){
this.wheels = wheels || 0;
this.color = color || '';
this.speed = speed || 0;
return this;
}
}.init(4,'red',120);
alert(car.speed); //=>120
这消除需要:
context : this,
wheels : 0,
color : '',
speed : 0,
...并提供了可能性:
var car = {
init : function(wheels,color,speed){
this.wheels = wheels || 0;
this.color = color || '';
this.speed = speed || 0;
return this;
}
},
redAndFast = car.init(4,'red',230),
threeWheeler = car.init(3,'yellowstriped',110);
[编辑]什么was我在想什么?如果你想要租车的更多情况下,你必须使用真实constructor
函数,而不是一个对象字面的:
var Car = function(){
return {
init : function(wheels,color,speed){
this.wheels = wheels || 0;
this.color = color || '';
this.speed = speed || 0;
return this;
}
}
},
redAndFast = new Car().init(4,'red',230),
threeWheeler = new Car().init(3,'yellowstriped',110);
这可以简化为:
var Car = function(wheels,color,speed){
this.wheels = wheels || 0;
this.color = color || '';
this.speed = speed || 0;
},
redAndFast = new Car(4,'red',230),
threeWheeler = new Car(3,'yellowstriped',110);
或者,如果你想攀附在一些init
像功能:
var Car = (function(){
function car(wheels,color,speed){
this.wheels = wheels || 0;
this.color = color || '';
this.speed = speed || 0;
}
return {
init: function(w,c,s){
return new car(w,c,s);
}
};
})(),
redAndFast = Car.init(4,'red',230),
threeWheeler = Car.init(3,'yellowstriped',110);
但是,嘿,发生了什么事我context
?你可能会问。那么,事实证明你毕竟不需要它。不是一个美丽而灵活的语言?
你究竟想要达到什么目的? 和它有何不同:'var car = new Car();' – 2011-05-08 21:00:13
一个Object对象没有this属性,只有Function对象。在一个函数中,'this'是一个属于激活对象(实际上是一个变量)的关键字,它不是一个公共属性。最后,函数的'this'由调用设置,不能静态设置(尽管可以使用ES5和* bind *)。 – RobG 2011-05-08 23:16:01