Home>Article>Web Front-end> Solution to the solution pointed to by this in js closure (code)

Solution to the solution pointed to by this in js closure (code)

不言
不言 Original
2018-08-23 15:47:01 2267browse

The content of this article is about the solution (code) pointed to by this in js closure. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The following is a question, for the sub-function defined in the object method, where does this point to when the sub-function is executed?
Three questions:
(1) What is the object this printed in the following code?
(2) Can this code achieve the function of increasing myNumber.value by 1?
(3) Without giving up the helper function, what modification methods can be used to achieve the correct function?

var myNumber = { value: 1, add: function(i){ var helper = function(i){ console.log(this); this.value += i; } helper(i); } } myNumber.add(1);

1. This points to the window object (because the execution of the anonymous function is global, so its this object points to the window);
2. The value cannot be increased by 1 (each function will be Automatically obtain two special variables, this and arguments. When the internal function searches these two objects, it will only search until its active object, so it cannot access the this object of the external function);
3. Modify the code to implement it correctly Function
Method 1:

var myNumber={ value:1, add:function(i){ var that=this;//定义变量that用于保存上层函数的this对象 var helper=function(i){ console.log(that); that.value+=i; } helper(i); } } myNumber.add(1);

Method 2:

var myNumber={ value:1, add:function(i){ var helper=function(i){ this.value+=i; } helper.apply(this,[i]);//使用apply改变helper的this对象指向,使其指向myNumber对象 } } myNumber.add(1);

Method 3:

var myNumber={ value:1, add:function(i){ var helper=function(i){ this.value+=i; }.bind(this,i);//使用bind绑定,和apply相似,只是它返回的是对函数的引用,不会立即执行 helper(i); } } myNumber.add(1);

Related recommendations:

How to judge browsing in js Is the server PC or mobile? (Two methods)

Two methods for calling self-executing functions in js

The above is the detailed content of Solution to the solution pointed to by this in js closure (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn