Skip to content

Commit

Permalink
learn bind
Browse files Browse the repository at this point in the history
  • Loading branch information
abstain23 committed Jun 3, 2020
1 parent 70b2b5d commit a35eeb2
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions 手写一个bind.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,33 @@ Function.prototype.myBind = function(context) {
}
//如果有构造函数

function Person() {
this.name = 'p'
console.log(this)
}
// var a = Person.bind({va:1})
var p = Person.call({ccc:'call'})

Function.prototype.myBind2 = function(ctx, ...args) {
const _this = this
const Temp = function() {}
const fn = function(...args2) {
return _this.apply(this instanceof fn ? this: ctx, [...args, ...args2])
}
// fn.prototype = _this.prototype 这样当我们直接修改fn.prototype的时候也会修改绑定函数的prototype

Temp.prototype = _this.prototype
fn.prototype = new Temp()
return fn
}

function Person() {
this.name = 'p'
console.log(this)
}

Person.prototype.pp ='pp'
var a = Person.myBind2({ccc:1})
console.log(new a())


0 comments on commit a35eeb2

Please sign in to comment.