[英]What's the difference between these two ways of writting a prototype function in JavaScript
Myfunction.prototype.updateMyFunction = function() {
//do something
};
Myfunction.prototype = {
updateMyfunction: function() {
//do something
}
};
They both produce identical results 他们都产生相同的结果
The first one is adding a property to Myfunction.prototype
, while the second one completely replacing the Myfunction.prototype
with a new object. 第一个是向
Myfunction.prototype
添加属性,而第二个Myfunction.prototype
用新对象完全替换Myfunction.prototype
。
The result will not be always identical. 结果将不会总是相同的。 Consider this case -
考虑这种情况-
Myfunction.prototype.oldMethod = function () {
};
Myfunction.prototype.updateMyFunction = function() {
//do something
};
After adding the last method, you will be able to access both oldMethod
and updateMyFunction
later. 添加完最后一个方法后,您以后可以访问
oldMethod
和updateMyFunction
。 If you do this - 如果您这样做-
Myfunction.prototype.oldMethod = function () {
};
Myfunction.prototype = {
updateMyfunction: function() {
//do something
}
};
then the oldMethod
will be removed from the prototype chain (since the prototype
itself is being replaced with a new object) and you will not be able to access it anymore. 那么
oldMethod
将从原型链中删除(因为prototype
本身已被新对象替换),您将无法再访问它。
The first one uses the already-existing prototype of MyFunction, while the second one replaces the prototype with a new object. 第一个使用MyFunction的现有原型,而第二个使用新对象替换该原型。
Some surprising problem with replacing the prototype: 替换原型存在一些令人惊讶的问题:
var MyFunction = function(){
};
var obj = new MyFunction();
MyFunction.prototype = {
updateMyfunction: function() {}
};
var obj2 = new MyFunction();
console.log(obj2 instanceof MyFunction) // true as expected
console.log(obj instanceof MyFunction) // false because the prototype changed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.