美文网首页
JS this 入门详解

JS this 入门详解

作者: 龚达耶 | 来源:发表于2019-06-13 19:05 被阅读0次

针对于this这个对象相信大家一开始在接触他的时候都比较头疼,这里放出两篇文章,大家可以阅读下,看下阮一峰老师是怎么解释的。

Javascript 的 this 用法

JavaScript 的 this 原理

接下来是我自己的理解

this对象是在运行时基于函数的执行环境绑定的。

在全局函数中this等于window,而当函数被作为某个对象的方法调用时,this等于那个对象。

//全局
function test() {
   console.log(this);
}
test();  // window
//对象方法
function test() {
   console.log(this);
}
var obj = new Object();
obj.x = 1;
obj.m = test;

obj.m(); //{x: 1, m: ƒ}


// 构造函数
function test() {
 this.x = 1;
}

var obj = new test();
console.log(obj) // {x: 1}
// apply, call
var x = 0;
function test() {
 console.log(this.x);
}

var obj = {};
var obj2 = {
  x:12
}
obj.x = 1;
obj.m = test;
obj.m.call() // 0 无参数全局
obj.m.call(obj2)// 12有参数当前对象

所以有了这上面四个例子我们就可以很好地解决阮老师的demo

var obj = {
  foo: function () { console.log(this.bar) },
  bar: 1
};

var foo = obj.foo;
var bar = 2;

obj.foo() // 1
foo() // 2

因为obj.foo()是调用对象方法所以就是指的上一级 1

而foo()是调用全局所以2

注意: 匿名函数执行环境具有全局性,因此this指向window。

    var name = "The Window";
    var object = {
        name: "My Object",
        getNameFunc: function() {
            return function() {
                return this.name;
            };
        }
    };
    console.log(object.getNameFunc()());

相关文章

网友评论

      本文标题:JS this 入门详解

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