JS原理性知识的函数实现

JS一些原理性的知识用函数自己实现

new

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const People = function(name) {
this.name = name
}
People.prototype.sayName = function() {
console.log('my name is ' + this.name)
}

// step1:创建一个新对象 obj
// step2:把 obj 的 __proto__ 指向 People.prototype 实现继承
// step3:执行构造函数,传递参数,改变this指向 People.call(obj, ...args)
// step4:结果是 null 和 undefined 时不处理
function _new(fn, ...arg) {
let obj = Object.create(fn.prototype)
let result = fn.call(obj, ...arg)
return result instanceof Object ? result : obj
}

let my = _new(People, 'Nola')

双向绑定

查看效果:地址

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
var input = document.getElementById('input')
var show = document.getElementById('show')
input.addEventListener('input', function(e) {
obj.text = e.target.value
})

// defineProperty 实现
var obj = {}
Object.defineProperty(obj, 'text', {
configurable: true,
enumerable: true,
get: function() {
return obj.text
},
set: function(newValue) {
input.value = newValue
show.innerText = newValue
}
})

// proxy 实现
var obj = new Proxy({}, {
get: function(obj, prop) {
return obj[prop]
},
set: function(obj, prop, newValue) {
obj[prop] = newValue
input.value = newValue
show.innerText = newValue
}
})

call

1
2
3
4
5
6
7
Function.prototype.call = function(context, ...args) {
context || (context = window)
context.fn = this
let result = eval(`context.fn(${args})`)
delete context.fn
return result
}

apply

1
2
3
4
5
6
7
Function.prototype.apply = function(context, args) {
context || (context = window)
context.fn = this
let result = eval(`context.fn(${args})`)
delete context.fn
return result
}

bind

1
2
3
4
5
6
Function.prototype.bind = function(context, args) {
if(typeof this !== 'function') return
context || (context = window)
let result = arg => this.apply(context, args.concat(arg))
return result
}