-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path手写一个bind.js
43 lines (36 loc) · 1.02 KB
/
手写一个bind.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//简易版本
// 返回一个函数 可以传入参数
Function.prototype.myBind = function(context) {
var _this = this
var context = context || window
//取出bind的第二个到后面的参数
var args = [...arguments].slice(1)
return function () {
return _this.apply(context, args.concat(...arguments))
}
}
//如果有构造函数
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())