js一个对象的prototype重新显式声明后不重新定义constructor,会产生什么后果?

function Person(name){
    this.name = name;
}
Person.prototype = {};// 清空prototype
Person.prototype.sayHello = function(){alert(this.name+"say Hello!");};

在定义 Person 类时清空了 Person.prototypenew Person 后似乎感受不到差异,prototype上的方法还是能调用。

是不是constractor不重定义影响不大,如果有影响,会在哪些方面产生影响?

阅读 2.8k
3 个回答

当然有影响了,关于 constructor 的介绍 MDN

由于你把 Person.prototype 清空了,比如你定义一个

var ming = new Person("xiaoming");
console.log(ming.constructor == Person); // false
console.log(ming.constructor == Object); // true

你也看到了,爷爷变成了爸爸,乱伦了。。

constructor 有时候很有用的。

function Person(name){
    this.name = name;
}
Person.prototype = {};
Person.prototype.sayHello = function(){console.log(this.name+"say Hello!");};
new Person(1).sayHello()//1say Hello!
Person.prototype = {};// 清空prototype
Person.prototype.sayHello2 = function(){console.log(this.name+"say Hello2!");};
new Person(1).sayHello() //报错
new Person(1).sayHello2() //1say Hello2!

prototype修改后原来的sayHello方法没了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题