- apply
/*
允许使用es6
*/
// Function.prototype.apply2 = function (context, args) {
// let fun_name = Symbol()
// context.fun_name = this
// let value = context.fun_name(...args)
// delete context.fun_name
// return value
// }
/*
不允许允许使用es6
*/
Function.prototype.apply2 = function (context, args) {
//手动封装symbol
function mySymbol(obj) {
let fun_name = Math.random() + '' + Date.now()
if (context.fun_name) {
return mySymbol()
}
return fun_name
}
let fun_name = mySymbol()
context.fun_name = this
let arr = []
for (let i = 0; i < args.length; i++) {
arr.push(`args[${i}]`)
}
let value = eval('context.fun_name(' + arr.join(',') + ')')
delete context.fun_name
return value
}
function helloWorld(a, b, c) {
console.log(a, b, c)
console.log('helloWorld!', a + b + c)
return a + b + c
}
let obj = {}
helloWorld.apply2(obj, [1, 2, 3])
2 . bind
Function.prototype.bind2 = function (context) {
let args = Array.from(arguments).slice(1)
let _this = this
function fbind() {
return _this.apply(
//当为new一个对象时 ,this应该指向这个构造体
this instanceof fbind ? this : context,
args.concat(arguments)
)
}
// fbind.prototype.__proto__=_this.prototype,让这个对象继承原型上的方法
fbind.prototype = Object.create(_this.prototype)
return fbind
}
let Cat = function (color, age) {
this.color = color
this.age = age
console.log(this.color, this.age)
}
Cat.prototype.helloWorld = function (a, b, c) {
console.log(this)
console.log(a, b, c)
console.log('helloWorld!', a + b + c)
return a + b + c
}
//bind为js原生的方法
let obj = {}
let cat1 = Cat.bind(obj, 'red', 3)
let ca1 = new cat1()
ca1.helloWorld(1, 2, 3)
//bind2为实现的方法
let cat2 = Cat.bind2(obj, 'red', 3)
let ca2 = new cat2()
ca2.helloWorld(4, 5, 6)