我正在尝试使用构造函数模式创建一个对象,并使用 Object.defineProperty 定义属性。
function random (a,b,c) {
var sample = null;
this.a = a;
this.b = b;
if(b && c){
this.sample(b,c);
}
Object.defineProperty(random, 'sample', {
get: function(){
console.log(b);
}
});
};
var foo = new random(10,1,2);
这会引发错误:未捕获类型错误:对象不是函数。 我做错了什么?请帮忙。
最佳答案
有几个问题:
- 在定义
sample
之前引用它 - 您在构造函数上定义
sample
(random
),但它应该在this
上。 - 缺少右括号。
- 您像调用函数一样调用
sample
,但您尚未将其定义为函数。defineProperty
中的函数是 getter,而不是方法本身。如果您想像这样编写代码,则需要 getter 来返回您的方法。
检查这个更正后的代码和注释:
function random (a,b,c) {
var sample = null;
this.a = a;
// First define, then call:
// Define on this, not on random:
Object.defineProperty(this, 'sample', {
get: function() {
// must return a function
return function (b) {
console.log(b);
};
}
}); // <-- missing bracket
// Moved after defineProperty:
if(b && c) {
this.sample(b,c); // note that you don't use the second argument
}
}
console.log(new random(1,2,3));
关于javascript - 声明具有参数问题的构造函数对象的 JavaScript 对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39175111/