构造函数
function Person(){}
Person.prototype = {}
Person.prototype.constructor == Person // false
class 类
class Person{}
Person.prototype = {}
Person.prototype.constructor == Person // true
为什么构造函数和 class 重写原型之后的表现不一致,是因为 class 的 prototype 属性不能重写吗?
没有找到相关的资料,希望看到的大佬指点一下
已解决
悬赏分:0
- 解决时间 2021-11-27 21:27
点赞 0反对 0举报 0
收藏 0
分享 3
回答3
最佳
-
Object.defineProperty 属性描述符
普通情况:
let obj = { name: 1 } obj = {} obj.name == 1 // false
输出一下 Class 属性描述符:
class Person{} Object.getOwnPropertyDescriptor(Person, 'prototype')
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: {} } const Person = {} Object.defineProperty(Person, 'prototype', { value: {} })
支持 0 反对 0 举报2021-11-27 09:17
-
class prototype 不能重写,会静默失败。
class Person{} Person.prototype = {a: 1} console.log(Person.prototype.a) // undefined
标准写法都是在类里定义
class Person { method() {} } console.log(Person.prototype.method) // function method
支持 0 反对 0 举报2021-11-27 10:18
-
class 类的特征:
- 内部所有定义的方法不可枚举
- 不能重写 prototype 属性(writable 默认为 false)
- 默认使用严格模式
支持 0 反对 0 举报2021-11-27 11:01