【问题标题】:Setting the scope of this [duplicate]设置这个[重复]的范围
【发布时间】:2013-02-09 20:32:02
【问题描述】:

您好,我正在尝试学习使用 jQuery 库 1.9 在 javascript 中以更加面向对象的方式工作。我正处于一个小项目中,我必须更改此对象的范围。这是我的 html :

<div id="contact">
<h2>Contact Me</h2>
<form action="#">
    <ul>
        <li>
            <label for="name">Name: </label>
            <input name="name" id="name">
        </li>

        <li>
            <label for="email">Email Address: </label>
            <input name="email" id="email">
        </li>

        <li>
            <label for="comments">What's Up?</label>
            <textarea name="comments" id="comments" cols="30" rows="10"></textarea>
        </li>
        <li>
            <input type="submit" value="Submit">
        </li>
    </ul>
</form>

这是我的 javascript

var contactForm = {
    contact : $('div#contact'),

    init : function(){
        this.contact.hide();
        $('<button></button>' , { 
            text : "Display Contact"
        }).insertAfter('article')
          .on('click' , this.show);
    },

    show : function(){
       $.proxy(contactForm , this)
       this.contact.slideDown();

    }
};

contactForm.init();

问题出在我的 show 方法上。我知道我可以使用 $.proxy() 设置“this”的范围。但我一定做错了,因为即使在 settign $.proxy 之后,“this”关键字仍然指的是按钮。

如何让这个“this”关键字引用“contactForm”对象

【问题讨论】:

  • 您好,我使用代理添加了更多解释以及您的代码的工作副本。请再次查看。 jsfiddle.net/Brnv2/4

标签: javascript jquery


【解决方案1】:

这应该可行:

.on('click', $.proxy(this.show, this));

并显示:

show: function() {
   this.contact.slideDown();
}

【讨论】:

    【解决方案2】:

    阅读有关代理的文档,它不会更改当前方法中的“this”上下文。代理的签名是$.proxy( myFunction, thisVar ),这意味着代理将返回函数myFunction,当它执行myFunction时,这个值将引用thisVar

    这能解决您的问题吗?

    这意味着您想将显示功能更改为:

    show : function(){
       $.proxy( function(){ this.slideDown() }, contactForm )();
    
    }
    

    这里有一个简单的例子来说明它是如何工作的

     f = $.proxy( function(){ console.log(this.msg); } , { msg: "hello world" });
     f(); // ==> should log to console "hello world"  
    

    这是fiddle to see it in action

    您还可以将参数传递给函数。例如:

     f = $.proxy( function(msg){ console.log([this,msg]); }, { topic:"my topic" } )
     f("hello world");
    

    查看fiddle 也可以看到这一点。

    最后但同样重要的是,这是fiddle with your code working like I suggested.

    【讨论】:

    • 我试过了,还是不行
    【解决方案3】:

    你的错误在这里:

    .on('click' , this.show)
    

    虽然这指的是this.show,但当show 随后作为事件处理程序被调用时,它不会将上下文设置为this。你有一个函数引用,但它最终与最初包含它的对象分离。

    你应该使用:

    .on('click', $.proxy(this.show, this))
    

    并从.show 中删除$.proxy 调用

    请注意,$.proxy() 旨在返回一个新的函数引用,该引用在调用时将始终具有给定的上下文。它对 current 函数的上下文没有任何作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-25
      • 2019-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多