1、JavaScript 中 This 的指向

一、普通函数中的 this

  1. var name = "蛮王", position = "上单";
  2. var obj = {
  3. name: "寒冰射手",
  4. objPosition: this.position,
  5. relationFun: function () {
  6. console.log(this.name + "的位置是:" + this.position);
  7. }
  8. };
  9. console.log(obj.objPosition); // 上单
  10. obj.relationFun(); // 寒冰射手的位置是:undefined

总结:
在普通函数中的this:
1、this 总是代表它的直接调用者(js 的 this 是执行上下文),例如:obj.relationFun,那么 relationFun 中的 this 就是 obj
2、在默认情况下,没有找到直接调用者,则 this 指向的是 window

再举例验证一下:

  1. var hero = "盲僧";
  2. function show (){
  3. console.log(this.hero); // 此时 this 指向 window
  4. }
  5. show(); // 盲僧
  1. function show (){
  2. var hero = "盲僧";
  3. console.log(this.hero); // 此时 this 指向 window, 在 window 未找到 hero
  4. }
  5. show(); // undefined

看到这里,普通函数中的 this 的指向问题,是不是就清晰很多了呢。

二、构造函数中的 this

来一起看下构造函数中的 this 指向问题吧,举例:

  1. function lolFun() {
  2. this.hero = "亚索";
  3. }
  4. var object = new lolFun;
  5. console.log(object.hero);

看到这个例子,咱们先讲个题外话。弱弱的问一句:函数是对象吗?
答案是肯定的。当然了,我们也可以验证一下

  1. lolFun instanceof Object // true

无论学习什么知识,凡事多问几个 “为什么” ?我相信,你将进步的很快!
那我们不妨再大胆一点问:对象是通过函数创建的吗?
答案也是肯定的。当聊到这里,估计会有小伙伴该有疑问了,那举例简单验证一下吧。

大多数情况下,我们是这样创建对象的:

  1. var obj = {
  2. name: "亚索",
  3. position: "中单",
  4. }

但实际上它底层上也是用函数创建的:

  1. var obj = new Object();
  2. obj.name = "亚索";
  3. obj.position = "中单";

此时的 Object 是函数 (function)

  1. typeof Object // function

关于函数与对象的关系,简单总结一下:对象是通过函数创建的,而函数又是一种对象


  1. function lolFun() {
  2. this.hero = "亚索";
  3. }
  4. var object = new lolFun;
  5. console.log(object.hero); // 亚索

OK,言归正传,继续讨论构造函数中的 this 指向。
这里能打印出来: “亚索”,按照 普通函数中 this 总结的两条,好像没法解释了,其实:
new 关键字是能够改变指针指向的。通过 new 关键字实例化,得到 object 对象,同时会将 lolFun 中的属性或者函数 “复制” 一份到 object 对象中。所以在 object 中找到了 hero 属性,自然就输出了:”亚索”。

其实,这样理解是可以的。但是,理解是不完整的,继续举例:

举例1:

  1. function lolFun() {
  2. this.hero = "亚索";
  3. return {};
  4. }
  5. var object = new lolFun;
  6. console.log(object.hero); // undefined

举例2:

  1. function lolFun() {
  2. this.hero = "亚索";
  3. return function () { };
  4. }
  5. var object = new lolFun;
  6. console.log(object.hero); // undefined

举例3:

  1. function lolFun() {
  2. this.hero = "亚索";
  3. return true;
  4. }
  5. var object = new lolFun;
  6. console.log(object.hero); // 亚索

举例4:

  1. function lolFun() {
  2. this.hero = "亚索";
  3. return null;
  4. }
  5. var object = new lolFun;
  6. console.log(object.hero);// 亚索

总结:
构造函数中的 this
1、如果返回了对象,则 this 指向的就是这个对象;如果无返回值或者返回值的不是对象,则 this 还是指向函数的实例
2、【特殊记忆】从举例4,可以得出结论,虽然 null 是对象,但是 this 还是指向函数实例了