gpt4 book ai didi

JavaScript:使用 Object.defineProperties()

转载 作者:行者123 更新时间:2023-11-28 15:31:21 24 4
gpt4 key购买 nike

我正在尝试学习如何使用 Object.defineProperties()。我正在使用以下代码:

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

Object.defineProperties(Person, {
sayHi : {
get : function() {return "Hello";},
enumerable : true
},
sayBye : {
get : function() {return "Bye";},
enumerable : true
}
});


var john = new Person('John', 'Doe');
console.log(john.sayHi());

但我不断得到:

TypeError: john.sayHi is not a function
console.log(john.sayHi());

有人可以告诉我这段代码有什么问题吗?

谢谢

最佳答案

嗯,您没有将 sayHi 定义为函数。这是将其定义为函数的方法:

var Person = function(firstName, lastName)
{
this.firstName = firstName;
this.lastName = lastName;
};
// Define the properties on the prototype, not the Person object itself
Object.defineProperties(Person.prototype, {
sayHi : {
get : function() {
return function() {
return "Hello, I am " + this.firstName + " " + this.lastName;
};
},
enumerable : true
},
sayBye : {
get : function() {
return function() {
return "Bye";
};
},
enumerable : true
}
});

var john = new Person('John', 'Doe');
console.log(john.sayHi());
console.log(john.sayBye());

准确地说:在您的代码中,john.sayHi 返回“Hello”字符串,它是一个字符串基元,因此绝对不是一个函数;-)

属性的获取函数必须返回一个函数才能实现您想要的功能。

为了给您更长的答案,请参阅以下其他实现,充分利用两件事:首先是 ES5 (Object.create()) 和 ES6 (Object .defineProperties())和JS的原型(prototype)性质(不使用new运算符,原型(prototype)继承):

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

Object.defineProperties(Person, {
sayHi : {
get : function() {return function() {return "Hello, I am " + this.firstName + " " + this.lastName;}},
enumerable : true
},
sayBye : {
get : function() {return function() {return "Bye";};},
enumerable : true
}
});

var Employee = Object.create(Person); // Employee inherits from Person

Employee.init = function(firstName, lastName, position) {
this.firstName = firstName;
this.lastName = lastName;
this.position = position;
};

Object.defineProperties(Employee, {
introduce : {
get : function() {return function() {
return this.sayHi() + ", " + this.position;
}},
enumerable : true
},
farewell : {
get: function() {return function() {
return this.sayBye() + ", it was a pleasure to meet you";
}},
enumerable: true
}
});

var john = Object.create(Employee); // john inherits from Employee
john.init('John', 'Doe', 'Manager');

console.log(john.sayHi()); // Inherited from Person
console.log(john.introduce()); // Inherited from Employee
console.log(john.sayBye()); // Inherited from Person
console.log(john.farewell()); // Inherited from Employee

JSFIddle demo

关于JavaScript:使用 Object.defineProperties(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27252371/

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