jQuery 插件上 属性 中未定义的对象方法引用

undefined reference to object method in it's property on jQuery plugin

我在第 27 行遇到问题 (fiddle: https://jsfiddle.net/hh82p4fj/1/)

为什么我的 属性 在同一个闭包中指向 undefined

"use strict";

function callself(instance, callback) { // saves 'this' state for reuse inside another function
    return function () {
        var argumentsList = [this], i;

        for (i = 0; i < arguments.length; i = i + 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) {
            /* this = Namespace
               that = jQuery element
               userInput = provided in line 30 as 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'); }; // this method should be returned as reference in line 27, but it can not reah 'this` - don't know why
};
new Namespace().initialize();
那里需要

callself,以保留 jQuery this 上下文和 ryginal 对象闭包。

问题是初始化的顺序。

您在脚本开始时使用了this.method,而this.method = function(){}尚未执行,因此在创建设置对象时未定义this.method的值。

var Namespace = function () {
    //this should be set before `this.method` is referred
    this.method = function () {
        console.info('method');
    };

    var settings = {
        handler: this.method
    };

    this.initialize = function () {
        $.fn.myPlugin = callself(this, function (that, userInput) {
            /* this = Namespace
               that = jQuery element
               userInput = provided in line 30 as parameter
            */
            console.log(this);
            console.log(that);
            console.log(userInput);
            console.log(settings.handler); // why why it's undefined?
        });

        $('body').myPlugin('someData');
    };

};
var settings = { handler: this.method };

分配给settings.handler 不是this.method
[=38的引用 =]但是this.method的值(在执行时未定义)

this.method 必须是 对象 才能被引用。


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 will be 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()