简体   繁体   中英

Declaring JavaScript Object property of a constructor object having arguments issue

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.

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)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM