据我了解,在JavaScript中,每个对象都有一个,prototype
并且它公开了一些默认属性。我有以下代码,试图通过设置两个对象的Year属性prototype
。但是两个电话都失败了。
toLocalString()
如果我无权访问该对象,该如何覆盖prototype
?请注意,以下代码用于对该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);
您确实可以访问prototype属性,但是它仅存在于上Function
。
var car = {
Make: 'Nissan',
Model: 'Altima'
};
这与以下内容相同:
var car = new Object();
car.Make = 'Nissan';
car.Model = 'Altima';
因此,car.__proto__ === Object.prototype
。
并且car.prototype === undefined
因为该prototype
属性仅存在于Function
s(正如我已经说过的)。
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
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句