javascript - undefined reference to object method in it's property on jQuery plugin -
i have problem in line #27 (fiddle: https://jsfiddle.net/hh82p4fj/1/)
why property points undefined
while it's in same closure?
"use strict"; function callself(instance, callback) { // saves 'this' state reuse inside function return function () { var argumentslist = [this], i; (i = 0; < arguments.length; = + 1) { argumentslist.push(arguments[i]); } return callback.apply(instance, argumentslist); }; } var namespace = function () { var settings = { handler: this.method }; this.initialize = function () { $.fn.myplugin = callself(this, function (that, userinput) { /* = namespace = jquery element userinput = provided in line 30 parameter */ console.log(this); console.log(that); console.log(userinput); console.log(settings.handler); // why why it's undefined? }); $('body').myplugin('somedata'); }; this.method = function () { console.info('method'); }; // method should returned reference in line 27, can not reah 'this` - don't know why }; new namespace().initialize();
callself
needed there, preserve both jquery this
context ando ryginal object closure.
var settings = { handler: this.method };
you assigned settings.handler
not reference this.method
but value of this.method
(which undefined @ execution moment)
this.method
must object referenced.
this.method = {}; //empty object var settings = { handler: this.method };
this.method
=>ref {}
settings.handler
=>ref {}
this.method = {}; //empty object var settings = { handler: this.method }; this.method = funtion(){}`// reference replaced
this.method
=>ref funtion(){}
settings.handler
=>ref {}
this.method = {}; //empty object var settings = { handler: this.method }; this.method.use = function(){}
this.method
=>ref {use: function(){}}
settings.handler
=>ref {use: function(){}}
function namespace(){ var settings = {}; this.initialize = function(){ document.write(settings.handler()) }; settings.handler = function(){return 'handled!'}; } new namespace().initialize()
Comments
Post a Comment