javaScript中的this指向小结

前言

先来看一个吐槽,出自王垠-编程的宗派: 在JavaScript里面,每个函数同时又可以作为构造函数(constructor),所以每个函数里面都隐含了一个this变量,当嵌套多层对象和函数的时候就发现没法访问外层的this,非得bind一下

继承和原型链

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.

this指向

1. 全局函数

this指向全局对象window,注意严格模式下,this为undefined

//[object Window]
alert(this); 			
function f(){
  alert(this)
}
f(); 

// undefined
function demo() {
  'use strict';
   alert(this); 
}
demo();

let a = 1 //let定义自己的作用域,不挂载至window
function fn() {
  var a = 2
  console.log(this.a)
}
fn() //undefined

2. 函数调用

this指向调用该方法的对象

let name = 'finget'
let obj = {
 name: 'FinGet',
 getName: function() {
   alert(this.name);
 }
}
obj.getName(); // FinGet

let fn = obj.getName;
fn(); //finget this -> window

3. 构造函数

this指向创建出的实例

function demo() {
  this.testStr = 'this is a test';
}
let a = new demo();
alert(a.testStr);  // 'this is a test'

4. 事件函数

元素绑定事件,事件触发后执行函数中,this指向的是当前元素

window.onload = function() {
 let $btn = document.getElementById('btn');
 $btn.onclick = function(){
   alert(this); // this -> 当前触发元素
 }
}

5. 箭头函数

箭头函数没有自己的this,需要看其外层的是否有函数,如果有,外层函数的this就是内部箭头函数的this,如果没有,则this是window

var name = 'my name is window';
var obj = {
    name: 'my name is obj',
      fn: function () {
          var timer = null;
          clearInterval(timer);
          timer = setInterval(() => {
              console.log(this.name);  //my name is obj
          }, 1000)
    }
}

6. 定时器

定时器setTimeout或setInterval,this指向全局对window

//定时器
setTimeout(function() {
   alert(this); // this -> window ,严格模式 也是指向window
},500)

var name = 'my name is window';
var obj = {
     name: 'my name is obj',
     fn: function () {
          var timer = null;
          clearInterval(timer);
          timer = setInterval(function () {
              console.log(this.name);  //my name is window, this指向window
          }, 1000)
     }
}

7. 回调函数

回调函数或匿名函数自调用,this指向全局对window

  • 函数内部的【this】指向于此函数的调用者(拥有者)。
  • 虽然【callback】函数定义于对象【o】的【say】方法中,但实际上由于【callback】是在【func】函数中进行的普通调用,那么【func】中的【callback】的调用者可以理解为是【window】对象
  • 当使用一个对象的未定义的属性时不会报错,并返回“undefined”,而直接使用一个未定义的变量时便会报错
//回调函数
var o = {
    age : 12,
    say : function() {
        function callback() {
            return this.age;
        }
        func(callback);
    }
};
function func(callback) {
    var name = "Xiao Ming";
    console.log(name + " is " + callback() + " years old.");
}
o.say(); //Xiao Ming is undefined years old.

8. call、apply、bind

  • call和apply:改变this指向后执行函数。

    • call(thisScope, arg1, arg2, arg3…); //多个参数
    • apply(thisScope, [arg1, arg2, arg3…]); //两个参数
  • bind:改变this指向后,返回函数。
    bind(thisScope, arg1, arg2, arg3…)

var person = {
  name: 'pig',
  say: function(a){
    alert(this.name + " say " + a)
  }
};
person.say('hello'); //pig say hello

var name = 'duck';
person.say.call(window, 'hello'); //duck say hello

var arr = [1, 2, 3, 4];
Math.max.apply(null, arr); //4, null表示不改变this指向

function multiply (x, y, z) {
    return x * y * z;
}
var double = multiply.bind(null, 2);
//Outputs: 24
console.log(double(3, 4));

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值