关于 Class 与 Prototype 的疑惑

构造函数

function Person(){}
Person.prototype = {}
Person.prototype.constructor == Person // false

class

class Person{}
Person.prototype = {}
Person.prototype.constructor == Person // true

为什么构造函数和 class 重写原型之后的表现不一致,是因为 classprototype 属性不能重写吗?

没有找到相关的资料,希望看到的大佬指点一下

阅读 3.5k
3 个回答

Object.defineProperty 属性描述符

普通情况:

let obj = { name: 1 }

obj = {}

obj.name == 1 // false

输出一下 Class 属性描述符:

class Person{}

Object.getOwnPropertyDescriptor(Person, 'prototype')
/*
{
    configurable:false
    enumerable:false
    writable:false
}
*/

writable = false 不可重写
模拟一下:

const Person = {}

Object.defineProperty(Person, 'prototype', {
  writable: false, // 其实默认就为false
  value: {
    constructor: 1
  }
})

Person.prototype = {}
console.log(Person.prototype.constructor === 1) // true

补充两种声明区别:

const Person = {
  prototype: {}
}
/*
{
    configurable:true
    enumerable:true
    writable:true
    value: {}
}
*/

const Person = {}
Object.defineProperty(Person, 'prototype', {
  value: {}
})
/*
{
    configurable:false
    enumerable:false
    writable:false
    value: {}
}
*/

class prototype 不能重写,会静默失败。

class Person{}
Person.prototype = {a: 1}
console.log(Person.prototype.a)  // undefined

标准写法都是在类里定义

class Person {
    method() {}
}
console.log(Person.prototype.method)  // function method

class 类的特征:

  • 内部所有定义的方法不可枚举
  • 不能重写 prototype 属性(writable 默认为 false
  • 默认使用严格模式
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题