当前位置:网站首页>js的call、apply、bind

js的call、apply、bind

2022-07-23 05:39:00 Vivqst

Function.prototype.call(thisArg,arg1,arg2)

使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数

Function.prototype.apply(thisArg,[arg1, arg2])

调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数

用途与call()类似,区别是接收的参数不一样,call接收参数列表,apply接收参数数组

function Person(name, age) {
    
	this.name = name
	this.age = age
	this.greeting = function() {
    
		console.log(this.name + ' is ' + this.age)
	}
}

function Teacher() {
    
	// Person.call(this, 'lisi', 18)
	Person.apply(this, ['lisi', '18'])
	this.subject = '语文'
}

var teacher = new Teacher()
var person = new Person('张三', '15')
person.greeting()    // 张三 is 15
teacher.greeting()   // lisi is 18
Function.prototype.bind(thisArg,arg1,arg2)

bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

原网站

版权声明
本文为[Vivqst]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qiansitong/article/details/114971632