有没有办法检查功能是否不同,即使它们来自同一原型(prototype)?
我问这个是因为我需要将函数存储在一个数组中,当我尝试删除其中一个时,它会删除所有函数,因为原型(prototype)是相同的。
例如,在下面的代码中,当比较两个函数时,程序将返回 true。
var Car = function(name) {
this.name = name;
};
Car.prototype.checkLights = function() {
// some calculation...
};
var Nissan = new Car('nissan');
var Toyota = new Car('toyota');
// this will return true even though functions came from different objects
console.log(Nissan.checkLights === Toyota.checkLights)
我不完全清楚你的要求(通过查看你的代码),但是你的新对象 Nissan
和 Toyota
都是 Car
的实例> 使用共享的 prototype
对象。
这意味着,无论您对原型(prototype) [函数/属性] 进行什么更改,都会反射(reflect)在其他对象中。
如果你想让他们独立行事,那么你可以这样做:-
成员函数
var Car = function(name) {
this.name = name;
// add as member function
this.checkLights = function(){
// some calculation...
};
};
var Nissan = new Car('nissan');
var Toyota = new Car('toyota');
console.log(Nissan.checkLights === Toyota.checkLights); // false
Now, I would highly advise against it unless you have a very specific case, this will create a new instance of checkLights()
function every time you run constructor of Car