Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

javascript - 函数中的“ this”关键字如何工作?(How does “this” keyword work within a function?)

I just came across an interesting situation in JavaScript.

(我刚刚遇到了一个有趣的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.

(在这些对象内部,使用了this指针。)

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指针指向的是在其上调用方法的类,而不是由文字创建的对象。)

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
}
  ask by rmeador translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(从我的另一篇文章拆解,这里有更多的比你想要了解这一点 。)

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的最重要的内容,并在没有意义的情况下对自己重复一遍。)

Javascript does not have classes (ES6 class is syntactic sugar ).

(Javascript没有类(ES6 class语法糖 )。)

If something looks like a class, it's a clever trick.

(如果某个东西看起来像一堂课,那是个聪明的把戏。)

Javascript has objects and functions .

(Javascript具有对象功能 。)

(that's not 100% accurate, functions are just objects, but it can sometimes be helpful to think of them as separate things)

((这不是100%准确的,函数只是对象,但有时将它们视为独立的东西会有所帮助))

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.

(这通常称为调用模式。)

There are four ways to invoke functions in javascript.

(有四种方法可以调用javascript中的函数。)

You can invoke the function as a method , as a function , as a constructor , and with apply .

(您可以将函数作为方法函数构造函数以及apply调用。)

As a Method(作为一种方法)

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

(方法是附加到对象的函数)

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

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.

(在此示例中,它将绑定到foo。)

As A Function(作为功??能)

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.

(如果您具有独立功能,则变量将绑定到“全局”对象,几乎总是在浏览器上下文中的window对象。)

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

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.

(闭包(它本身就是一个话题)可以解决这个问题,因此,如果您将bar作为回调调用,它仍然具有引用。)

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

(注意:在use strict模式下,如果用作功能,则this功能不受全局限制。)

(It is undefined ).

(( undefined )。)

As a Constructor(作为建设者)

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 .

(根据您正在使用的命名约定(TestObject),这也可能是您正在做的事情,也是使您绊倒的原因 。)

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

(您可以使用new关键字将函数作为构造函数调用。)

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

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.

(使用那个=这个技巧/模式的变量。)

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.

(有人认为,构造器/新关键字是Java /传统OOP程序员的骨干,是创建类似于类的方式的一种方法。)

With the Apply Method(使用Apply方法)

Finally, every function has a method (yes, functions are objects in Javascript) named "apply".

(最后,每个函数都有一个名为“ apply”的方法(是的,函数是Javascript中的对象)。)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...