在ES5中,更改Animal類的原型會影響到之后實例化的對象
function Animal () {}
var a1 = new Animal()
Animal.prototype = {sayhi(){}}
var a2 = new Animal()
console.log('1 -- '+ a1.sayhi) // undefined
console.log('2 -- '+ a2.sayhi) // function sayhi(){}
因為Animal的prototype屬性writable。
Object.getOwnPropertyDescriptor(Animal, 'prototype')
/*
{
configurable: false
enumerable: false
value: Object { sayhi: sayhi() }
writable: true
?}
*/
在ES6中,使用class創(chuàng)建的類,修改其原型不會影響后面實例化的對象
class Person {}
var p1 = new Person()
Person.prototype = {sayhi(){}}
var p2 = new Person()
console.log('1 -- '+ p1.sayhi) // undefined
console.log('2 -- '+ p2.sayhi) // undefined
因為Person 的prototype屬性是unwritable。
Object.getOwnPropertyDescriptor(Person, 'prototype')
/*
{
configurable: false
enumerable: false
value: Object { ... }
writable: false
?}
*/