用初始值创建一个javascript对象,怎么做?

时间:2011-06-08 18:51:19

标签: javascript

    objCar = function(values){
     this = values;
     race = function(){
      alert('car model:'+this.model+' car brand: '+this.brand+' was joined the race');
     };
    };

    car = new objCar({'brand':'ford','model':'fiesta'});
    car.race;

我想objCar以json值为例,并且这些值可以在构造函数中传递,之后我可以调用在objCar的构造函数内创建的race函数,这可能吗?当我尝试这样做时,我会收到它:

  

左侧无效分配   错误源代码:[Parar neste erro]   this = values;

TNX。

3 个答案:

答案 0 :(得分:0)

function Car(values) {
    var  _this = this;

    values = values || {}; // in case the argument is undefined.

    this.brand = values["brand"] || ""; // empty string for default brand
    this.model = values["model"] || ""; // empty string for default model

    this.race = function() {
        alert('car model: '+ _this.model + ' car brand: ' + _this.brand + ' has joined the race');
    }
}

var car = new Car({'brand':'ford','model':'fiesta'});

car.race();

答案 1 :(得分:0)

你写的函数构造函数都错了。这应该纠正一些事情:

function objCar(values) {
    this.race = function() {
        alert('car model: ' + values.model + ' car brand: ' + values.brand + ' was joined the race');
    };
};

var car = new objCar({
    brand: 'ford',
    model: 'fiesta'
});
car.race();

答案 2 :(得分:0)

您只想将值中的所有属性复制到此中。您无法重新分配this是什么。

function Car(values) {

    for (var key in values) {
      this[key] = values[key];
    }

    this.race = function() {
        alert('car model: ' + this.model + 
              ' car brand: ' + this.brand + ' just joined the race');
    };
};

var car = new Car({
    brand: 'ford',
    model: 'fiesta'
});
car.race();

这是另一种方法,这更像是你想要做的, 即将传入的对象用作this; http://jsfiddle.net/mendesjuan/s3sap/

function Car() {
    this.race = function() {
        alert('car model: ' + this.model + 
              ' car brand: ' + this.brand + ' just joined the race');
    };
    return this;
};

var car = Car.apply({
    brand: 'ford',
    model: 'fiesta'
});
car.race();

或者另一种方式,哦,我喜欢JS OO以及百万种方法来做同样的事情。

function Car() {
    this.race = function() {
        alert('car model: ' + this.model + 
              ' car brand: ' + this.brand + ' just joined the race');
    };
};

var car = {
    brand: 'ford',
    model: 'fiesta'
};
Car.apply(car);

我认为这些都不是最好的方法,我宁愿使用原型而不是基于闭包的面向对象。 http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html