访问Javascript对象原型

24

据我了解,在JavaScript中每个对象都有一个原型prototype,并公开一些默认属性。我有以下代码,我正在尝试通过prototype设置两个对象的年份属性。但是这两个调用都失败了。

如果我没有访问prototype,我该如何覆盖任何对象的toLocalString()?请注意,以下代码是用于测试prototype属性,但我的意图是覆盖toLocalString()方法。

var car = {
    Make: 'Nissan',
    Model: 'Altima'
};

car.Year = 2014;
alert(car.Year);

alert(car.prototype); // returns undefined

car.prototype.Year = 2014; // Javascript error

// --------------

function Car() {
    this.Make = 'NISSAN';
    this.Model = 'Atlanta';
}

var v = new Car();
v.prototype.Year = 2014; // JavaScript error
alert(v.prototype);

1
在您的底部示例中,应该是Car.prototype.Year = 2014 - 您在对象函数上设置了原型,而不是已创建的实例。 - tymeJV
你是指要使用 toLocaleString() 而不是 toLocalString() 吗?还是你想要实现自己的方法 toLocalString() - keenthinker
请查看这个答案 - frogatto
2
prototype 属性属于 函数。当使用 new 调用该函数以构造实例对象时,函数会使用该 prototype 属性。在非函数对象上设置 prototype 没有任何效果。 - apsillers
2个回答

11

你确实可以访问原型属性,但它只存在于Function上。

var car = {
    Make: 'Nissan',
    Model: 'Altima'
}; 

这与以下代码相同:

var car = new Object();
car.Make = 'Nissan';
car.Model = 'Altima'; 

因此,car.__proto__ === Object.prototype

并且由于prototype属性仅出现在Function上(如我已经说过的那样),所以car.prototype === undefined

function Car() {
    this.Make = 'NISSAN';
    this.Model = 'Atlanta';
}

这里 Car.prototype 指向一个 Object 实例,因为 Car 是一个函数,并且当函数声明被评估时,它们的 prototype 被设置为一个 Object 实例。

Car.prototype.Year = 2014; //all Car *instances* will have a Year property set to 2014 on their prototype chain.

var c = new Car(); //create an instance
console.log(c.Year); //2014

在对象的原型链上重写一个方法,只需要在对象上创建一个相应的方法即可:

var myObject = new Object();
myObject.toLocaleString = function() {
  //my own implementation
};

6
你可能想要修改构造函数的原型(prototype):
function Car(year, make, model) {
  this.year  = year;
  this.make  = make;
  this.model = model;
}

Car.prototype.toLocaleString = function() {
  return [this.year, this.make, this.model].join(' ');
};

var civic = new Car(2014, 'Honda', 'Civic');
civic.toLocaleString(); // => "2014 Honda Civic"

这篇MDN关于Object.prototype的文章可能会有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接