gpt4 book ai didi

javascript - getOwnPropertyDescriptor 有值时返回 undefined

转载 作者:行者123 更新时间:2023-12-03 09:46:44 25 4
gpt4 key购买 nike

我已经花了一个小时试图解决 getOwnProperty 返回未定义的问题,我检查了我的笔记并找不到原因,请检查一下,或者更好地解释我为什么会出现这种行为???这里的主要目标只是覆盖扩展另一个方法的属性。

这里是 jsfiddle

var Person = function(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
};

Object.defineProperties(Person.prototype, {
sayHi : {
value : function() {
return "Hi there";
},
writable: true,
enumerable : true
},

fullName : {
get : function() {
return this.firstName + " " + this.lastName;
},
configurable : true,
enumerable : true
}

});

var createEmployee = function(firstName, lastName, ocupation) {

var employee = new Person(firstName, lastName);
employee.ocupation = ocupation;

/*over-w sayHi*/

var sayHifn = employee.sayHi.bind(employee);

employee.sayHi = function() {
return sayHifn() + " my name is " + this.firstName;
};

/*over-w fullName*/

var fullName = Object.getOwnPropertyDescriptor(employee, "fullName");
var fullNameFn = fullName.get.bind(employee);

Object.defineProperty(employee, 'fullName', {
get : function() {
return fullNameFn() + " this is o-w ";
}

});

return employee;

};

var record = createEmployee('jhon', 'doe', 'eng');
console.log(record);

最佳答案

您获得 undefined 的原因是employee变量没有名为 fullName 的“自己的”属性.该属性属于 Person.prototype .

试试这个:

var fullName = Object.getOwnPropertyDescriptor(Person.prototype, "fullName");

如果您更改该行,则其余代码应按原样工作。

供引用(强调):

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDescriptor

The Object.getOwnPropertyDescriptor() method returns a property descriptor for an own property (that is, one directly present on an object, not present by dint of being along an object's prototype chain) of a given object.

关于javascript - getOwnPropertyDescriptor 有值时返回 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21460791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com