javascript - Where is the property in self-defining function? -
i have question self-defining function.
var scareme = function(){ console.log("boo!"); var instance = this; scareme = function(){ console.log("double boo!"); return instance; } } scareme.prototype.nothing = true; var un1 = new scareme(); console.log(un1.nothing); //true scareme.prototype.everything = true; var un2 = new scareme(); console.log(un1 === un2); //true
it works expected.
console.log(un2.everything); //undefined
where can 'everything' property?
it won't work because once scareme
called, overriding scareme
function when try change prototype after initial call changing prototype of second method not first method had created instance. changes prototype not reflected in instance.
one possible solution override prototype of second object first one
var scareme = function () { console.log("boo!"); var instance = this, proto = scareme.prototype; scareme = function () { console.log("double boo!"); return instance; } scareme.prototype = proto; } scareme.prototype.nothing = true; var un1 = new scareme(); console.log('nothing', un1.nothing); //true scareme.prototype.everything = true; var un2 = new scareme(); console.log(un1 === un2); //true console.log('everything', un1.everything); //true
demo: fiddle
another way write same like
var scareme = (function () { var instance; return function () { if (instance) { return instance; } instance = this; } })();
demo: fiddle
Comments
Post a Comment