Reputation: 2484
I'm trying to create an object using constructor pattern and also define properties using 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);
This throws an error: Uncaught TypeError: object is not a function. What am I doing wrong ? Please Help.
Upvotes: 0
Views: 44
Reputation: 350272
There are several issues:
sample
before it is definedsample
on the constructor (random
), but it should be on this
.sample
like a function, but you had not defined it as one. The function in defineProperty
is the getter, not the method itself. If you want to code it like this, you need the getter to return your method.Check this corrected code with comments:
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));
Upvotes: 1