call
傳入一個(gè)指定的對(duì)象和若干指定的參數(shù)的前提下調(diào)用指定對(duì)象的屬性和方法
var obj = {
name : 'harry'
}
function getName () {
console.log(this.name);
}
getName.call(obj) //harry
模擬實(shí)現(xiàn),第一步
- 給對(duì)象添加方法
- 執(zhí)行方法
- 刪除方法
//以上代碼相當(dāng)于給obj添加了getName方法并調(diào)用它
var obj = {
name : 'harry',
getName: function () {
console.log(this.name);
}
}
obj.getName() //harry
//但同時(shí)給obj添加了一個(gè)屬性方法兽愤,我們可以刪除它
delete obj.getName
Function.prototype.myCall = function (context) {
//判斷有沒(méi)有傳入context吼旧,如果沒(méi)有就將其設(shè)為window
var context = context || window
context.fn = this
context.fn()
delete context.fn
}
第二步,call還可以傳入不定數(shù)目的參數(shù)
- 從 Arguments 對(duì)象中取值,取出第二個(gè)到最后一個(gè)參數(shù)朴则,然后放到一個(gè)數(shù)組里
- 使用slice方法肄鸽,獲取參數(shù)
Function.prototype.myCall = function (context) {
//判斷有沒(méi)有傳入context帆喇,如果沒(méi)有就將其設(shè)為window
var context = context || window
context.fn = this
let args = [...arguments].slice(1)
context.fn(...args)
delete context.fn
}
第三步词身,call可以有返回值
var obj = {
value: 1
}
function bar(name) {
console.log(this.value);
return {
value : this.value,
name
}
}
let res = bar.call(obj, 'harry')
console.log(res); //{value: 1, name: 'harry'}
補(bǔ)全代碼
Function.prototype.myCall = function (context) {
//判斷有沒(méi)有傳入context,如果沒(méi)有就將其設(shè)為window
var context = context || window
context.fn = this
let args = [...arguments].slice(1),
res = null
res = context.fn(...args)
delete context.fn
return res
}
測(cè)試代碼
var foo = {
value : 1,
}
function bar (name, age) {
this.name = name
this.age = age
console.log(this.value);
console.log(`我是${this.name},我${this.age}歲了`);
}
Function.prototype.myCall = function (context) {
var context = context || window
context.fn = this
let args = [...arguments].slice(1),
res = null
res = eval(context.fn(...args))
delete context.fn
return res
}
let res = bar.myCall(foo, 'potter', 12) //1 我是potter,我12歲了
apply
apply和call相似番枚,apply參數(shù)接受一個(gè)指定的對(duì)象和數(shù)組
Function.prototype.myApply = function (context) {
//判斷有沒(méi)有傳入context,如果沒(méi)有就將其設(shè)為window
var context = context || window
context.fn = this
//判斷有沒(méi)有傳入第二個(gè)參數(shù)數(shù)組
if (arguments[1]) {
res = context.fn(...arguments[1])
} else {
res = context.fn()
}
delete context.fn
return res
}
var obj = {
value : 1
}
function bar (name, age) {
this.name = name
this.age = age
console.log(this.value);
console.log(`我是${this.name},我${this.age}歲了`);
}
bar.apply(obj, ['potter', 13])