javascript - js一个对象的prototype重新显式声明后不重新定义constructor,会产生什么后果?
天蓬老师
天蓬老师 2017-04-11 13:32:08
0
3
439
function Person(name){ this.name = name; } Person.prototype = {};// 清空prototype Person.prototype.sayHello = function(){alert(this.name+"say Hello!");};

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

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

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

모든 응답 (3)
PHPzhong

传送门

    小葫芦

    当然有影响了,关于 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方法没了

        최신 다운로드
        더>
        웹 효과
        웹사이트 소스 코드
        웹사이트 자료
        프론트엔드 템플릿
        회사 소개 부인 성명 Sitemap
        PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!