开发者

Creating a javascript object with initial values, how?

    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;

I want to objCar be started with a json values for example and that these values can be passed in constructor and after that i can call the race function that is created inside the constructor of objCar, is that possible? when i try to do this i receive it:

inva开发者_JAVA技巧lid assignment left-hand side error source line: [Parar neste erro] this = values;

tnx.


You've written the function constructor all wrong. This should correct things:

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


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


You just want to copy all the properties from values into this. You cannot reassign what this is.

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

Here's another way to do it, which is more like what you were trying to do, that is to use the passed in object as 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();

Or yet another way, oh how I love JS OO and the million ways to do the same thing.

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

And I think neither of these is the best way, I'd rather use the prototype instead of closure based object orientation. http://js-bits.blogspot.com/2010/08/javascript-inheritance-done-right.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜