Javascript对象字面量,如何解决上下文? [英] Javascript object literal, how to solve context?
问题描述
我想开始组织我的代码,所以我想使用对象字面量。在下面的情况下,我做一个伪类。我希望 init()
可以作为一个构造函数,但不幸的是,我没有看到如何根据对象上下文设置属性。
I would like to start organizing my code properly, so I want to use object literals. In the following case, I'm doing a pseudo class. I would like that init()
could work as a constructor, but unfortunately, I'm not seeing how to set attributes based on object context.
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);
推荐答案
声明对象字面量。你可以做什么:
You can't immediately run a function like that whilst declaring an object literal. What you can do:
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,
...并提供以下可能性:
...and offers the possibility for:
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);
[编辑 >是我在想?如果你想要更多的Car实例,你必须使用真实的构造函数
函数,而不是对象常量:
[edit] What was I thinking? If you want more instances of Car, you'll have to use a real constructor
function instead of an object literal:
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
like function:
Or if you wanted to cling on to some init
like function:
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);
< ?你可以问。好吧,事实证明,你不需要它毕竟。是不是javascript是一个美丽和灵活的语言?
But hey, what happened to my context
? you may ask. Well, it turns out you didn't need it after all. Isn't javascript a beautiful and flexible language?
这篇关于Javascript对象字面量,如何解决上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!