这个运算符在javascript中 [英] this operator in javascript

查看:124
本文介绍了这个运算符在javascript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有JavaScript代码,如

Suppose I have JavaScript code like

      myClass = function(){
          function doSomething(){
              alert(this); // this1 
          }
      } 
      alert(this); //this2

这两个'this'对象是指什么?

What those two 'this' objects are refer for??

推荐答案

全局执行上下文中的 this 值是指全局对象,例如:

The this value in the global execution context, refers to the global object, e.g.:

this === window; // true

对于函数代码,它实际上取决于你如何调用函数,例如,在以下情况下隐式设置值:

For Function Code, it really depends on how do you invoke the function, for example, the this value is implicitly set when:

调用不带基础对象的函数参考

Calling a function with no base object reference:

myFunc();

值也将参考全局对象。

The this value will also refer to the global object.

调用绑定为对象属性的函数

obj.method();

值将引用 obj

使用 new 运算符

Using the new operator:

new MyFunc();

值将引用一个新的创建的对象继承自 MyFunc.prototype

The this value will refer to a newly created object that inherits from MyFunc.prototype.

此外,您可以在调用函数时显式设置该值,使用 致电 apply 方法,例如:

Also, you can set explicitly that value when you invoke a function, using either the call or apply methods, for example:

function test(arg) {
  alert(this + arg);
}
test.call("Hello", " world!"); // will alert "Hello World!"

调用和<$ c之间的差异$ c> apply 是 apply ,你可以使用数组或参数正确传递任意数量的参数对象,例如:

The difference between call and apply is that with apply, you can pass correctly any number of arguments, using an Array or an arguments object, e.g.:

function sum() {
  var result = 0;
  for (var i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}

var args = [1,2,3,4];
sum.apply(null, args); // 10

// equivalent to call
sum(1,2,3,4); // 10

如果第一个参数值调用 apply null undefined 值将引用全局对象。

If the first argument value of call or apply is null or undefined, the this value will refer to the global object.

(请注意,这将在未来发生变化, ECMAScript 5,其中调用应用传递 thisArg 值无需修改)

(note that this will change in the future, with ECMAScript 5, where call and apply pass the thisArg value without modification)

这篇关于这个运算符在javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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