Accessing Javascript object prototype
本问题已经有最佳答案,请猛点这里访问。
据我所知,在javascript中,每个对象都有一个
如果我没有访问
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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 2 3 4 | var car = { Make: 'Nissan', Model: 'Altima' }; |
这与:
1 2 3 | var car = new Object(); car.Make = 'Nissan'; car.Model = 'Altima'; |
所以,
而
1 2 3 4 | function Car() { this.Make = 'NISSAN'; this.Model = 'Atlanta'; } |
这里,
覆盖对象原型链上的方法与在对象上创建相应的方法一样简单:
1 2 3 4 | var myObject = new Object(); myObject.toLocaleString = function() { //my own implementation }; |
您可能希望修改构造函数函数原型:
1 2 3 4 5 6 7 8 9 10 11 12 | 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" |
这篇关于