“这个”怎么样?关键字在函数内工作? [英] How does "this" keyword work within a function?

查看:164
本文介绍了“这个”怎么样?关键字在函数内工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在JavaScript中遇到了一个有趣的情况。我有一个类,其方法使用object-literal表示法定义多个对象。在这些对象中,正在使用这个指针。从程序的行为,我推断出这个指针指的是调用该方法的类,而不是文字创建的对象。

I just came across an interesting situation in JavaScript. I have a class with a method that defines several objects using object-literal notation. Inside those objects, the this pointer is being used. From the behavior of the program, I have deduced that the this pointer is referring to the class on which the method was invoked, and not the object being created by the literal.

这似乎是随意的,尽管这是我希望它的工作方式。这是定义的行为吗?跨浏览器安全吗?有没有任何理由可以解释为什么它超出规范如此说明的方式(例如,它是否是一些更广泛的设计决策/哲学的结果)?简化代码示例:

This seems arbitrary, though it is the way I would expect it to work. Is this defined behavior? Is it cross-browser safe? Is there any reasoning underlying why it is the way it is beyond "the spec says so" (for instance, is it a consequence of some broader design decision/philosophy)? Pared-down code example:

// inside class definition, itself an object literal, we have this function:
onRender: function() {

    this.menuItems = this.menuItems.concat([
        {
            text: 'Group by Module',
            rptletdiv: this
        },
        {
            text: 'Group by Status',
            rptletdiv: this
        }]);
    // etc
}


推荐答案

从我的另一篇文章中解读,这里比你想知道的更多这个

Cannibalized from another post of mine, here's more than you ever wanted to know about this.

在开始之前,这是最重要的事情记住Javascript,并在没有意义时重复自己。 Javascript没有类(ES6 语法糖)。如果看起来像一个类,这是一个聪明的把戏。 Javascript包含对象功能。 (这不是100%准确,函数只是对象,但将它们视为单独的东西有时会有所帮助)

Before I start, here's the most important thing to keep in mind about Javascript, and to repeat to yourself when it doesn't make sense. Javascript does not have classes (ES6 class is syntactic sugar). If something looks like a class, it's a clever trick. Javascript has objects and functions. (that's not 100% accurate, functions are just objects, but it can sometimes be helpful to think of them as separate things)

this 变量附加到函数。每当您调用一个函数时,都会被赋予一定的值,具体取决于您调用该函数的方式。这通常称为调用模式。

The this variable is attached to functions. Whenever you invoke a function, this is given a certain value, depending on how you invoke the function. This is often called the invocation pattern.

有四种方法可以在javascript中调用函数。您可以将该函数作为方法,作为函数,作为构造函数调用,并使用 apply

There are four ways to invoke functions in javascript. You can invoke the function as a method, as a function, as a constructor, and with apply.

方法是一个附加到对象的函数

A method is a function that's attached to an object

var foo = {};
foo.someMethod = function(){
    alert(this);
}

当作为方法调用时,将是绑定到函数/方法所属的对象。在这个例子中,这将绑定到foo。

When invoked as a method, this will be bound to the object the function/method is a part of. In this example, this will be bound to foo.

如果你有一个独立的立场函数,这个变量将被绑定到全局对象,几乎总是在浏览器的上下文中的 window 对象。

If you have a stand alone function, the this variable will be bound to the "global" object, almost always the window object in the context of a browser.

 var foo = function(){
    alert(this);
 }
 foo();

这可能是绊倒你,但不要心疼。很多人认为这是一个糟糕的设计决定。由于回调是作为一个函数而不是一个方法调用的,这就是为什么你会看到看似不一致的行为的原因。

This may be what's tripping you up, but don't feel bad. Many people consider this a bad design decision. Since a callback is invoked as a function and not as a method, that's why you're seeing what appears to be inconsistent behavior.

许多人通过这样做来解决问题类似的,嗯,这个

Many people get around the problem by doing something like, um, this

var foo = {};
foo.someMethod = function (){
    var that=this;
    function bar(){
        alert(that);
    }
}

你定义一个变量 指向。关闭(它自己的主题)保持 ,所以如果你把bar称为回调,它仍然有一个参考。

You define a variable that which points to this. Closure (a topic all it's own) keeps that around, so if you call bar as a callback, it still has a reference.

注意:在中使用严格模式(如果用作函数),未绑定到全局。 (它是 undefined )。

NOTE: In use strict mode if used as function, this is not bound to global. (It is undefined).

您还可以将函数作为构造函数调用。根据你正在使用的命名约定(TestObject),这也可能就是你正在做的事情,也是你绊倒的事情

You can also invoke a function as a constructor. Based on the naming convention you're using (TestObject) this also may be what you're doing and is what's tripping you up.

使用new关键字调用函数作为构造函数。

You invoke a function as a Constructor with the new keyword.

function Foo(){
    this.confusing = 'hell yeah';
}
var myObject = new Foo();

当作为构造函数调用时,将创建一个新的Object,并且 this 将绑定到该对象。同样,如果你有内部函数并且它们被用作回调,你将把它们作为函数调用,而这个将被绑定到全局对象。使用那个=这个技巧/模式的var。

When invoked as a constructor, a new Object will be created, and this will be bound to that object. Again, if you have inner functions and they're used as callbacks, you'll be invoking them as functions, and this will be bound to the global object. Use that var that = this trick/pattern.

有些人认为构造函数/ new关键字是Java /传统OOP程序员抛出的骨头,作为创建类似东西的方法到了类。

Some people think the constructor/new keyword was a bone thrown to Java/traditional OOP programmers as a way to create something similar to classes.

最后,每个函数都有一个方法(是的,函数是对象)在Javascript)名为申请。 Apply允许您确定 this 的值,并允许您传入一组参数。这是一个无用的例子。

Finally, every function has a method (yes, functions are objects in Javascript) named "apply". Apply lets you determine what the value of this will be, and also lets you pass in an array of arguments. Here's a useless example.

function foo(a,b){
    alert(a);
    alert(b);
    alert(this);
}
var args = ['ah','be'];
foo.apply('omg',args);

这篇关于“这个”怎么样?关键字在函数内工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆