function Name(name,params) {
this.name = name
this.params = params
}
function title(age,params,name) {
var a = Name.bind(this)
a(name,params)
this.age = age
}
var a = new title('123','234','345')
console.log(a);
let obj1 = {0:'a',1:'b',length:2}
let obj2 = {0:'a',1:'b',length:2}
let obj3 = {0:'a',1:'b',length:2}
let re1 = Array.prototype.push.call(obj1,'c','d')
let re2 = Array.prototype.push.apply(obj2,['c','d'])
let re3 = Array.prototype.push.bind(obj3,'c')
re3('d')
console.log(obj1,re1);
console.log(obj2,re2);
console.log(obj3,re3);
function foo(arg) {
return {name:this.name,arg:arg}
}
Function.prototype.mybind = function mybind(fn,obj) {
const fn = this
return function () {
return fn.apply(obj,arguments)
}
}
let tom = {name:'tom的name'}
let bob = {name:'bob的name'}
let bar = foo.mybind(tom)
let bar1 = foo.bind(tom)
console.log(bar(111));
console.log(bar.call(bob,222));
console.log(bar1.call(bob,222));
console.log(foo.call(bob,333));
function foo(e) {
console.log(e,this.id);
}
var obj = {id:'123'}
var arr = Object.keys(obj)
arr.forEach(foo,obj)
let obj = {0:'a',1:'b',length:2}
let myObj = {
_push: function (...e) {
let len = this.length
let arg = arguments.length
for (let i = 0; i < arg; i++) {
this[len+i] = e[i]
}
this.length = len + arg
return this.length
}
}
myObj._push.apply(obj,['c','d'])
myObj._push.bind(obj,'d')('e','f')
小结
- this指向优先级问题 new > bind(显式-硬绑定) > apply/call(显式绑定) > 隐式绑定 > 默认绑定
- 其中 new 可以用bind 实现; bind可以用 call 实现; call可以用 forEach 实现; forEach 就是 function + for