我正在尝试学习如何使用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());
有人可以告诉我这段代码有什么问题吗?
由于
答案 0 :(得分:3)
好吧,你没有将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" string,这是一个字符串原语,因此绝对不是函数; - )
属性的get函数必须返回一个函数才能达到你想要的效果。
为了给你一个更长的答案,请看下面的其他实现,充分利用两件事:首先是ES5(Object.create()
)和ES6(Object.defineProperties()
)的新功能和原型性质JS(不使用new
运算符,原型继承):
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
答案 1 :(得分:1)
替换
get : function() {return "Hello";} with
get : function() {return function() {return "Hello";};}