分配后,JavaScript函数绑定(此关键字)将丢失 [英] JavaScript function binding (this keyword) is lost after assignment

查看:97
本文介绍了分配后,JavaScript函数绑定(此关键字)将丢失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是JavaScript中最神秘的功能之一,在将对象方法分配给其他变量后,绑定(此关键字)丢失

this is one of most mystery feature in JavaScript, after assigning the object method to other variable, the binding (this keyword) is lost

var john = {
  name: 'John',
  greet: function(person) {
    alert("Hi " + person + ", my name is " + this.name);
  }
};

john.greet("Mark"); // Hi Mark, my name is John

var fx = john.greet;  
fx("Mark"); // Hi Mark, my name is 

我的问题是:

1)作业背后发生了什么? var fx = john.greet;
是按价值复制还是按参考复制?
fx和john.greet指向两个不同的函数,对吗?

1) what is happening behind the assignment? var fx = john.greet; is this copy by value or copy by reference? fx and john.greet point to two diferent function, right?

2)因为fx是一个全局方法,所以范围链只包含全局对象。 Variable对象中 属性的值是多少?

2) since fx is a global method, the scope chain contains only global object. what is the value of this property in Variable object?

推荐答案

1) fx john。 greet 指的是同一个函数对象,对象的赋值操作,引用

1) fx and john.greet are referring to the same function object, the assignment operation for objects, works by reference.

对于原始值,例如字符串数字布尔值 undefined null ,将复制该值。

For primitive values, like String, Number, Boolean undefined or null, a copy of the value will be made.

2)值是指全局对象。

2) The this value refers to the global object.

this value不是变量对象的属性它与范围链无关,是一个特殊的保留字,当调用函数(您也可以通过 call 明确设置它)。

The this value is not a property of the Variable Object and it has nothing to do with the scope chain, is a special reserved word, and it is determined implicitly when a function is called (you can also set it explicitly via call or apply).

JavaScript内部处理 参考类型 ,它由两个组成部分组成,基础对象属性名称,当调用一个函数时,这个值是通过获取基础对象隐式确定的(由内部 GetValue 操作)。

JavaScript internally handles a Reference type, which consists of two components, the base object and the property name, when a function is invoked, the this value is determined implicitly by getting the base object (by the internal GetValue operation).

最后,隐式设置的最后一种情况是使用 new 运算符,关键字将引用新创建的对象。

And finally, the last case where this is set implicitly is when you invoke a function with the new operator, the this keyword will refer to a newly created object.

所以简要说明,这是这个如何隐式

So in brief, here is how this works implicitly:

1-当一个函数被调用时作为方法(该函数作为对象的成员被调用):

1- When a function is called as a method (the function is invoked as member of an object):

obj.method(); // 'this' inside method will refer to obj

2- A 正常函数调用:

2- A normal function call:

myFunction(); // 'this' inside the function will refer to the Global object
// or 
(function () {})();

3-使用 new 运算符时:

var obj = new MyObj(); // 'this' will refer to a newly created object.

这篇关于分配后,JavaScript函数绑定(此关键字)将丢失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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