美文网首页
javaScript 中 this 引用

javaScript 中 this 引用

作者: BGING | 来源:发表于2019-03-04 18:09 被阅读0次

this 在 js 中是一个很重要的知识点,在 js 中 this 指向的是当前的作用域,所以获取 this 的值就是获取当前作用域的值。不过今天在看这方面的知识的时候也发现了不一样的地方。

例子
// 这是基本的代码
var bar = 2;
var obj = {
    bar: 1,
    foo: function () { console.log(this.bar) },
};        
var foo = obj.foo;
obj.foo();  // 1
foo();   // 2

如果按照 js 对 this 的定义可以分析一下刚才的代码

var bar = 2;
var obj = {
    bar: 1,
    foo: function () { console.log(this.bar) },
};
obj.foo();  // 这里 this 指代的是 obj 这个对象,所以得到的 1
var foo = obj.foo; // foo 是 window 的变量
foo();  // 默认等于 window.foo() 所以这里的 this 指代的是 window,那么得到的结果就应该是 2
  • bind 更改 this 的指向
    在调用的地方直接修改 this 指向
// 将 var foo = obj.foo 替换下。
var foo = obj.foo.bind(obj);
foo() // 1

还有两种方式可以更改 call 、apply;其实 call、 apply 和 bind 更改 this 针对的都是 function。只有function调用的时候才会指向this作用域;因此,就有很多写法了。可以是匿名方法,内置对象构造函数等等。

// 匿名方法
let arr = [{name:"a"}, {name:"b"}];
for(let i =0; i< arr.length; i++){
  (function(i){
      console.log(`#${i} name:${this.name}`)
  }).call(arr[i],i);
}
// #0 name:a
// #1 name:b

// 内置对象
Array.prototype.push.call(this, 1)
  • call 和 apply 始终有点费解。来个例子
    需要在代码里嵌套实现
function a() {
    this.name = "a";
    this.getName = function () {
        console.log(this.name);
    }
}
function b() {
    this.name = "b";
    a.call(this);
}
new b().getName() // a

call 和apply 更像实现了“继承” 将 a 构造函数的属性和方法被 b 继承了。当然作用域也确实是更改了。

相关文章

网友评论

      本文标题:javaScript 中 this 引用

      本文链接:https://www.haomeiwen.com/subject/luniuqtx.html