JS中call()、apply()、bind()的区别及应用

89 阅读1分钟

区别

不同之处:

call、apply的区别:接受参数的方式不一样。

bind:不立即执行。而apply、call 立即执行。

三者相同点:

都可以用来改变this的指向

call()和apply()比较

不同点:参数书写方式不同

call()的第一个参数是this要指向的对象,后面传入的是参数列表,参数可以是任意类型,当第一个参数为null、undefined的时候,默认指向window;

apply():第一个参数是this要指向的对象,第二个参数是数组

let obj = {} //定义一个空的对象
function f(x,y){
    console.log(x,y,this) //this是指obj
}
f.apply(obj,[1,2]) //后面的值需要用[]括起来
f.call(obj,1,2)    //直接写

call()和bind()比较

不同点:call()改过this的指向后,会再执行函数,bind()改过this后,不执行函数,会返回一个绑定新this的函数

function f(){
    console.log("我被调用了");
    console.log(this) 
}
let obj = {};
f.call(obj)          //直接调用函数
let g = f.bind(obj); //bind()不能调用函数
g();                 //此时才调用函数

用法

利用call()判断数据类型

在判断数据类形式使用typeof,一般不是太准确的,只能用来判断基本数据类型和function。我们可以使用Object.prototype.toString.call()方法来判断一个数据的数据类型

console.log(Object.prototype.toString.call([]))              // [object Array]
console.log(Object.prototype.toString.call({}))              // [object Object]

实现继承

        function Person(name){
			this.name = name;
		}
		Person.prototype.eat = function(){console.log(this.name+"正在吃饭")}
		
		function Student(name,age){
			// 执行Person,传入this
			Person.call(this, name);//继承构造函数
			this.age = age;
		}
		// 继承Person 的原型
		Student.prototype = Object.create(Person.prototype);
		// 修正Student构造函数
		Student.prototype.constructor = Student;
		// 挂载新的方法
		Student.prototype.study = function(){console.log(this.age+"岁的"+this.name+"正在学习")}
		
		var s1 = new Student("张三",18);