JavaScript中的原型问题
我有以下代码:JavaScript中的原型问题,javascript,prototype,Javascript,Prototype,我有以下代码: function University(name) { this.name = name } University.prototype = { sayName: function() { console.log(this.name) }, toString: function() { console.log("WUSTL") } }; var univ = new University("Washington
function University(name) {
this.name = name
}
University.prototype = {
sayName: function() {
console.log(this.name)
},
toString: function() {
console.log("WUSTL")
}
};
var univ = new University("Washington University");
console.log(univ instanceof University);
console.log(univ.constructor == University); // false
console.log(univ.constructor == Object); // true
有人能解释为什么“University”实例的构造函数改为Object而不是University吗?因为您重写了知道构造函数身份的原始原型。您需要在重写原型时重置原型:
University.prototype.constructor=University代码>。关于原型的一个有用的例子。