以不同的方式调用javascript函数

时间:2022-06-08 23:55:04

Consider I have a function as:

考虑我有一个功能:

function test1() {
  this.x= 10;
  this.fun = function() {
   return function() {
   console.log(this.x);
  };
 };
}


var obj = new test1();
var returnFun = obj.fun();

There are 2 ways of calling this function:

调用此函数有两种方法:

returnFun();

and

returnFun.call(obj);

why is it that the first method is not recommendable and what will be the value for "this" in two different contexts? Will var obj = new test1(); statement create a new object and set the value of "this" as prototype?

为什么第一种方法不值得推荐,在两种不同的背景下“this”的价值是什么?将var obj = new test1();语句创建一个新对象并将“this”的值设置为原型?

1 个解决方案

#1


2  

why is it that the first method (returnFun();) is not recommendable?

为什么第一种方法(returnFun();)不值得推荐?

There's nothing wrong with that method at all.

这种方法完全没有问题。

what will be the value for "this" in two different contexts?

在两种不同的背景下,“this”的价值是多少?

The value of this in the first example will be the outer scope the function was defined in, which would be the window.

第一个示例中的this值将是函数定义的外部作用域,即窗口。

To change the scope of this programmatically, use either the call() or apply() methods, as you have done in the second example. This means that for the second example, this in the function would refer to the obj variable.

要以编程方式更改此范围,请使用call()或apply()方法,如第二个示例中所述。这意味着对于第二个示例,函数中的this将引用obj变量。

#1


2  

why is it that the first method (returnFun();) is not recommendable?

为什么第一种方法(returnFun();)不值得推荐?

There's nothing wrong with that method at all.

这种方法完全没有问题。

what will be the value for "this" in two different contexts?

在两种不同的背景下,“this”的价值是多少?

The value of this in the first example will be the outer scope the function was defined in, which would be the window.

第一个示例中的this值将是函数定义的外部作用域,即窗口。

To change the scope of this programmatically, use either the call() or apply() methods, as you have done in the second example. This means that for the second example, this in the function would refer to the obj variable.

要以编程方式更改此范围,请使用call()或apply()方法,如第二个示例中所述。这意味着对于第二个示例,函数中的this将引用obj变量。