Lokomotywa
Lokomotywa

Reputation: 2844

`this`-context in constructor unclear

What I want is an object with a value (clazz) and a function(test), where the function delivers the value.

https://jsfiddle.net/pzy9dm9x/2/

var Clazz = function(object) {
     for(o in object) {
     this[o] = object[o];
     }
  return this;
}
var Construct = Clazz({
                 clazz : "xyz",
                 test  : function () {
                           console.log(this.clazz);
                         }
                 });
var a = new Construct();
console.log(a);
a.test();

I want: xyz

I get: TypeError: Construct is not a constructor

Upvotes: 1

Views: 31

Answers (1)

Bergi
Bergi

Reputation: 664297

Your Clazz function does not return a constructor function. I think you actually want something like

function Construct() {
    Clazz.call(this, {
        clazz : "xyz",
        test  : function () {
            console.log(this.clazz);
       }
    });
}

Upvotes: 1

Related Questions