【问题标题】:Accessing Javascript object prototype [duplicate]访问 Javascript 对象原型 [重复]
【发布时间】:2014-11-26 18:22:44
【问题描述】:

据我了解,在 JavaScript 中,每个对象都有一个 prototype,并且它公开了一些默认属性。我有以下代码,我试图通过prototype 设置两个对象的 Year 属性。但是两个调用都失败了。

如果我无权访问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);

【问题讨论】:

  • 在你的底部示例中,它应该是Car.prototype.Year = 2014 - 你在对象函数上设置原型 - 而不是创建的实例。
  • 你的意思是toLocaleString()而不是toLocalString()还是你想实现自己的方法toLocalString()
  • 请看this answer
  • prototype 属性属于一个函数。该函数在使用new 调用时使用该prototype 属性来构造实例对象。在非函数对象上设置prototype 无效。

标签: javascript prototype javascript-objects


【解决方案1】:

您确实可以访问原型属性,但它只存在于Functions。

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

这与:

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

所以,car.__proto__ === Object.prototype

car.prototype === undefined 作为prototype 属性仅存在于Functions(正如我已经说过的)。

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

【讨论】:

    【解决方案2】:

    你可能想修改构造函数原型:

    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 article on Object.prototype 可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-01
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多