函数内this指向不同的场景与改变this指向的几种方式

(一)函数内this指向不同的场景

1.1 普通函数时调用时,this指向window
	function fn () {
		console.log(this); //this指向 window
	}
	fn();
1.2 构造函数调用时,this指向当前所创建的对象
	// 构造函数
	function Student(name, age) {
	   this.name = name;
	   this.age = age;
	   console.log(this);
	}
	var stu1 = new Student('张三', 19); // this → 当前所创建的这个学生实例对象
1.3 对象的方法调用时,this指向方法所属的对象
	// 构造函数
	function Student (name, age) {
		this.name = name;
		this.age = age;
		
	}
	// 原型中的方法
	Student.prototype.sayHi = function() {
		console.log(this);
		console.log( this === stu1); //true
	};
	var stu1 = new Student('张三', 19); 
	stu1.sayHi();  // this → stu1
1.4 事件绑定的方法,this 指向事件源
div id="box" style="width: 30px; height: 30px; background-color: brown;"></div>
    // id为box的div元素对象
    var box = document.getElementById('box');
    // 为box注册事件
    box.onclick = function () {
        console.log(this); 
        //<div id="box" style="width: 30px; height: 30px; background-color: brown;"></div>
    };
1.5定时器函数,this指向window
    setInterval(function () {   // 省略了window 其实等于window.setInterval
        console.log(this);  //window
    }, 500);

(二)改变改变函数内的this指向

改变this的方式:函数有三个方法可以改变内部的this:call、apply、bind。

2.1 call方法

语法:

	函数名.call(thisArg, arg1, arg2, ...);
  • thisArg,在 函数运行时指定的 this 值。若传null或undefined,则函数内部this指向window
  • arg1, arg2, …指定的参数列表
   var obj = {
        0: 100,
        1: 200,
        2: 300,
        3: 400,
        length: 4
    }
    // obj.push(500); // 报错 对象中不存在这个方法
    // 借用数组的
    Array.prototype.push.call(obj, 500);
    console.log(obj); //添加成功 obj里面多一个4:500 length变为 5
2.2 apply方法

语法:

	函数名.apply(thisArg, [argsArray])
  • thisArg,在 函数运行时指定的 this 值。若传null或undefined,则函数内部this指向window
  • argsArray,是一个数组,数组中存放函数调用时需要传入的实参。

和call方法一样,唯一不同的时,函数或方法被借用时,apply以数组的方式存放实参。

    var nums = [11,66,33,44,55,77,22];
    var max = Math.max.apply(Math,nums);
    console.log(max);  //77
2.3 bind方法

语法:

	var 变量 = 函数名.bind(thisArg, arg1, arg2, ...);
  • thisArg,在 函数运行时指定的 this 值。若传null或undefined,则函数内部this指向window
  • arg1, arg2, …指定的参数列表

和call使用方式一样,不一样的时,使用bind时,借用的函数不会被立即执行,而是返回一个新的函数,若要执行,需要自己调用。

    var obj = {
        age: 18
    };
    // id为box的div元素对象
    var box = document.getElementById('box');
    // 为box注册事件
    box.onclick = function () {
        console.log(this.age);   //18
    }.bind(obj);
    setInterval(function () {
        console.log(this.age);
    }.bind(obj), 500);            //18 18 18 ...
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值