首页 > 其他 > 详细

this的指向问题及修改指向

时间:2018-11-13 10:57:28      阅读:151      评论:0      收藏:0      [点我收藏+]

this指的当前对象,如果在全局访问内使用this,则指向当前页面的window; 如果在函数中使用this,则this是指代什么是根据当前函数在什么对象上调用。

1 console.log(this === window); // true
2 console.log(window.alert === this.alert); // true
3 console.log(this.parseInt(‘021‘, 10)); //21
parseInt(string, radix);
// 在只使用一个参数时,是将其转为整数
// radix取值是2~36,表示当前数是几进制,并将这个数转为十进制,当不在这个范围时,会输出NaN

函数中的this是运行时决定的,而不是函数定义时。

 1 foo() {
 2     console.log(this.name);
 3 }
 4 var name = ‘global‘;
 5 foo(); // global
 6 var obj = {
 7     name: ‘block‘,
 8     foo: foo
 9 };
10 obj.foo(); // block

全局函数call和apply可以改变this的指向:

1 foo() {
2     console.log(this.name);
3 }
4 var name = ‘global‘;
5 var obj = {
6     name: ‘block‘
7 };
8 foo.apply(window); // global
9 foo.call(obj); // block

call和apply的唯一区别是,apply在传参数时,apply的参数要放在一个数组里,而call不需要。

 在JavaScript中,函数也是个对象:

 1 function foo() {
 2      if (this === window) {
 3         console.log(this is window);
 4     }
 5 }
 6 foo.boo= function() {
 7     if (this === window) {
 8         console.log(this is window);
 9     } else {
10         console.log(this is foo);   
11     }
12 }
13 // 等价于 window.foo
14 foo(); // this is window
15 
16 foo.boo(); // this is foo
17 
18 // 可以用call改变函数中this指向
19 foo.boo.call(window); // this is window

对象中的嵌套函数的this指向不是当前对象,而是window

 1 let name = ‘window‘;
 2 let obj = {
 3     name: ‘obj‘,
 4     getName: function() {
 5         console.log(this.name);
 6         return function() {
 7             console.log(this.name)
 8         }
 9     }
10 };
11 obj.getName()(); // obj   window     

解决上述问题的三种方法:

1、使用函数的bind方法,绑定当前this

 1 let name = ‘window‘;
 2 let obj = {
 3     name: ‘obj‘,
 4     getName: function() {
 5         console.log(this.name);
 6         return function() {
 7             console.log(this.name)
 8         }.bind(this);
 9      }
10  };
11 obj.getName()(); // obj   obj

2、使用变量将上面的this接收一下,然后下面不适用this,使用那个变量

3、使用ES6的箭头函数

 1 let name = ‘window‘;
 2 let obj = {
 3     name: ‘obj‘,
 4     getName: function() {
 5         console.log(this.name);
 6         return () => {
 7             console.log(this.name)
 8         }
 9     }
10 };
11 obj.getName()(); // obj   obj 

 

this的指向问题及修改指向

原文:https://www.cnblogs.com/sltk/p/9948106.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!