使用class声明对原型的影响

在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创建的类,修改其原型不会影响后面实例化的对象

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
​}
*/
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容