pun*_*bit 2 javascript closures this
我想开始正确组织我的代码,所以我想使用对象文字.在下面的例子中,我正在做一个伪类.我希望它init()可以作为构造函数,但不幸的是,我没有看到如何基于对象上下文设置属性.
var car = {
context : this,
wheels : 0,
color : '',
speed : 0,
init : (function(x){
console.log(x);
x.wheels = 4;
x.color = 'red';
x.speed = 120;
})(context)
};
console.log(car.color);
Run Code Online (Sandbox Code Playgroud)
在声明对象文字时,您不能立即运行这样的函数.你可以做什么:
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
Run Code Online (Sandbox Code Playgroud)
这消除了以下需求:
context : this,
wheels : 0,
color : '',
speed : 0,
Run Code Online (Sandbox Code Playgroud)
...并提供以下可能性:
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);
Run Code Online (Sandbox Code Playgroud)
[ 编辑 ]我在想什么?如果你想要更多的Car实例,你将不得不使用真正的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);
Run Code Online (Sandbox Code Playgroud)
哪个可以简化为:
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);
Run Code Online (Sandbox Code Playgroud)
或者如果你想坚持一些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);
Run Code Online (Sandbox Code Playgroud)
但是,嘿,发生了什么事context?你可能会问.好吧,事实证明你毕竟不需要它.javascript不是一种美观而灵活的语言吗?
| 归档时间: |
|
| 查看次数: |
1904 次 |
| 最近记录: |