Object.defineproperty如何作用到类上或者说构造函数上。试了下好像只能作用的对象实例上functionPerson(name,age){this._name=namethis._age=age}Person.prototype.say=function(){console.log(this._name)}lethuixu=newPerson('huixu',18)letlili=newPerson('lili',25)Object.defineProperty(huixu,"_name",{value:'xxx'})//作用在对象实例上是有效的//Object.defineProperty(Person,"_name",{value:'xxx'})无效huixu.say()//huixulili.say()//lili
2 回答
UYOU
TA贡献1878条经验 获得超4个赞
Object.defineProperty()方法会直接在一个对象上定义一个新属性functionPerson(name,age){this._name=namethis._age=age}Object.defineProperty(Person,"_name",{value:'xxx'})Person._name;//xxx这么定义属性是有效的,不管是上面说的构造函数,还是对象。但并不是定义在原型上,所以对应的实例对象无法继承。如果直接在Person.prototype原型上定义属性,就可以看到效果。Object.defineProperty(Person.prototype,"_name",{value:'xxx'})Person._name;//undefinedvarobj=newPerson('other',18)obj.say()//xxxobj._name;//'xxx'
繁花如伊
TA贡献2012条经验 获得超12个赞
看了你修改后的问题,你给Person添加的属性不会被实例化的对象继承的,实例只会继承Person.prototype上的属性,建议再去好好理解原型和原型链可以的啊classFun{}Object.defineProperty(Fun,'aa',{value:'fdsfd'})Fun.aa//"fdsfd"也可以添加enumerable为true,让添加的属性可枚举,具体参考MDNObject.defineProperty(Fun,'aa',{value:'fdsfd',enumerable:true})Object.keys(Fun)//["aa"]
添加回答
举报
0/150
提交
取消