0

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.

5
  • How are you calling the function? Commented Aug 26, 2016 at 21:54
  • you can't pass arguments to a getter Commented Aug 26, 2016 at 21:55
  • var caller = new random(1,2,3); Commented Aug 26, 2016 at 21:55
  • What is this.cache? Commented Aug 26, 2016 at 22:00
  • I removed arguments from getter but still getting the same error. Commented Aug 26, 2016 at 22:05

1 Answer 1

1

There are several issues:

  • You reference sample before it is defined
  • You define sample on the constructor (random), but it should be on this.
  • There was a closing parenthesis missing.
  • You call 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));

Sign up to request clarification or add additional context in comments.

1 Comment

Did this answer suit your needs? Could you accept or leave a comment?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.