2016-05-11 10 views
1

Was ich will ist ein Objekt mit einem Wert (clazz) und eine Funktion (test), wo die Funktion den Wert liefert.`this-context in constructor unklar

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

Ich möchte: xyz

ich: TypeError: Construct is not a constructor

Antwort

1

Ihre Clazz Funktion eine Konstruktorfunktion nicht zurück. Ich glaube, du willst etwas wie

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