为了方便,大部分人都是直接使用字面量来初始化对象,咱们知道原型对象是建立函数自带的,若是使用字面量来初始化至关于重写原型对象,这样就会致使一些以下问题。函数
问题:
重写以后,原型对象的constructor不在指向原型对象所在的函数prototype
function demo1 () { } demo1.prototype = { show: function() {console.log('execute success!')} } demo1.prototype.constructor再也不指向demo1
既然有了问题,那天然有解决问题的方法code
方法就是让构造函数从新指向原先得对象 function demo1 () {} demo1.prototype = { constructor: demo1, show: function() {console.log('execute success!')} }
可是这样写又有了新问题,[[Enumerable]]默认是true,而原先的构造函数默认是false,这时候咱们能够修改对象的属性,修改对象的属性天然要用到强大的defineProperty啦对象
function demo1 () {} demo1.prototype = { show: function() {console.log('execute success!')} } Object.defineProperty(demo1.prototype, 'constructor', { enumerable: false, value: demo1 })
好啦,大功告成,就是这样啦原型