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

时间:2015-06-15 09:21:36

标签: javascript jquery jquery-plugins namespaces closures

我在第27行(小提琴:https://jsfiddle.net/hh82p4fj/1/

中遇到问题

为什么我的财产在同一个关闭时指向onOptionsItemSelected()

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(); ,以保留jQuery callself上下文和ryginal对象闭包。

2 个答案:

答案 0 :(得分:4)

问题是初始化的顺序。

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');
    };

};

答案 1 :(得分:1)

var settings = { handler: this.method };

指向settings.handler 而不是参考this.method {{ 1}}(执行时未定义)

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

this.method
  

this.method = {}; //empty object var settings = { handler: this.method }; =&gt; ref {}   
this.method =&gt; ref {}

settings.handler
  

this.method = {}; //empty object var settings = { handler: this.method }; this.method = funtion(){}`// reference will be replaced =&gt; ref funtion(){}   
this.method =&gt; ref {}

settings.handler
  

this.method = {}; //empty object var settings = { handler: this.method }; this.method.use = function(){} =&gt; ref {use:function(){}}   
this.method =&gt; ref {use:function(){}}

<小时/>
settings.handler