Javascript对象文字,如何解决上下文

Javascript object literal, how to solve context?

本文关键字:解决 上下文 何解决 对象 文字 Javascript      更新时间:2023-09-26

我想开始正确地组织我的代码,所以我想使用对象文字。在下面的例子中,我正在做一个伪类。我希望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);

你不能在声明对象文字时立即运行这样的函数。您可以执行的操作:

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);

[编辑]我在想什么?如果你想要更多的 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);

可以简化为:

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怎么了?你可能会问。好吧,事实证明你毕竟不需要它。JavaScript不是一种美丽而灵活的语言吗?

var Car = function() {
    this.wheels = 4;
    this.color = 'red';
    this.speed = 120;
}
var car = new Car();

最好为此类任务使用普通构造函数。

对象文字适用于单例。如果你想要一个可实例化的对象,你需要学习js oop是如何工作的,并且只使用函数对象。