如何指定在构造中使用此

How to assign use this in a construct

本文关键字:何指定      更新时间:2023-09-26

当谈到javascript构造时,我有点初学者。我尝试使用jquery,但没有取得多大成功。以下是我的代码的简化版本:

var field1 = {
        fieldId:"#field1",
        field:"",
        init:function(){
            this.field = this;
            $.ajax({
                type:"GET",
                url:'some/url/to/get/values/from',
                cache:false,
                success: function(data){
                    alert(field.fieldId);
                }
            }); 
        }
};
field1.init();

基本上,我想能够在成功事件中打印出field.fieldid,但我最终得到了一些最意想不到的东西。我讨厌每次都要写field1.field.fieldid,因为当我弄清楚如何使用extends和类似的东西时,这会毁了我。

当我发出警报(field.fieldId)时,有人能帮我把"#field1"弄出来吗?

这是的经典案例,您必须记住this。在您的情况下,最简单的答案是init函数中的一个局部变量:

var field1 = {
        fieldId:"#field1",
        field:"",
        init:function(){
            var self = this;                      // <=== change here
            $.ajax({
                type:"GET",
                url:'some/url/to/get/values/from',
                    cache:false,
                success: function(data){
                    alert(self.fieldId);          // <=== and here
                }
            }); 
        }
};
field1.init();

或者,使用ajax函数的context参数:

var field1 = {
        fieldId:"#field1",
        field:"",
        init:function(){
                                                  // <=== change here (no `this.field = this;`)
            $.ajax({
                type:"GET",
                url:'some/url/to/get/values/from',
                cache:false,
                context: this,                    // <=== and here
                success: function(data){
                    alert(this.fieldId);          // <=== and here
                }
            }); 
        }
};
field1.init();

基本上,在JavaScript中,函数调用期间this的值完全由函数的调用方式定义,而不是像其他一些语言(C++、Java、C#…)中那样在哪里定义。当jQuery调用ajax函数的success回调时,它必须将this设置为某个值。默认情况下,它将它设置为一个表示ajax调用设置的对象,但使用context,您可以告诉jQuery将其设置为其他对象,从而允许您在回调中使用this来表示与调用ajax时的this相同的含义。

第一个解决方案利用了这样一个事实,即success回调是对init调用上下文中的闭包(别担心,闭包并不复杂),因此通过创建一个变量(self)并赋予其值this,我们可以通过闭包中的self可靠地引用对象(success回调)。


在JavaScript中设置this的方式:

  1. 当您通过从对象属性获取函数引用作为与调用相同的表达式的一部分来调用函数时,函数调用中的this将是从中获取属性的对象。因此:

    var obj = {
        firstName: "Fred",
        speak: function(msg) {
            alert(this.firstName + " says " + msg);
        }
    };
    

    然后

    obj.speak("hi");   // alerts "Fred says hi", because `this = obj` within the call
    

    请注意,它必须是与调用相同的表达式的一部分。这不起作用:

    var s = obj.speak; // Getting a reference to `obj`'s `speak`
    s("hi");           // alerts "undefined says hi", because `this` is not
                       // `obj` during the call
    
  2. 使用CCD_ 20或CCD_。这些是所有JavaScript函数的特性。它们允许您调用函数,并明确设置调用期间this的值。因此,给定上面的obj

    var s = obj.speak; // Getting a reference to `obj`'s `speak`
    s.call(obj, "hi"); // alerts "Fred says hi", we explicitly made `this = obj`
                       // within the call
    

    callapply之间的唯一区别是,当您使用call时,如果您想将参数传递给函数,您可以将它们作为离散参数包含在call中,如上所述(请注意,我们刚刚将"hi"作为第二个参数传递给callcall将其作为第一个参数传递到函数)。对于apply,而不是无限数量的离散参数,第二个参数是要传递给函数的参数的数组

    // Example 1: Passing no arguments, no difference.
    // These calls do the same thing.
    func.call(obj);
    func.apply(obj);
    // Example 2: Passing one argument (these calls do the same thing).
    func.call(obj, arg);
    func.apply(obj, [arg]); // note that it's in an array
    // Example 3: Passing two arguments (these calls do the same thing).
    func.call(obj, arg1, arg2);
    func.apply(obj, [arg1, arg2]); // Again, the args are in an array