avatar

目录
JavaScript之new和bind

new实现的功能:

  1. 返回一个返回对象的函数;
  2. 返回对象的原型链(proto)链上构造函数的prototype;
  3. 利用apply给构造函数指定this引用;
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function _new(fn){
return function() {
var o = { '__proto__': fn.prototype };
fn.apply(o, arguments);

return o;
};
}

function Person(name) {
this.name = name;
}
const person = _new(Person)('aa');
console.log(person);

bind实现的功能:

  1. 返回一个绑定了上下文(context)的函数;
  2. 利用apply达到绑定的目的;
  3. 考虑new调用bind返回的函数(稍复杂);
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Function.prototype._bind = function(context) {
var self = this; // self是函数
var args = Array.prototype.slice.call(arguments, 1);
var fbound = function() {
var bindArgs = Array.prototype.slice.call(arguments);
// 平常调用时,环境为context
// new 构造函数方式调用时,这环境指向this
self.apply(this instanceof self ? this : context, args.concat(bindArgs));
}
// 修改返回函数的 prototype 为绑定函数的 prototype,实例就可以继承函数的原型中的值
fbound.prototype = this.prototype;
return fbound;
}

const foo = {
value: 1
};
function bar() {
console.log(this.value);
}
const bindFoo = bar.bind(foo);
bindFoo(); // 1
文章作者: 盛顺炎
文章链接: https://www.shengshunyan.xyz/2018/10/22/JavaScript%E4%B9%8Bnew%E5%92%8Cbind/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 果实的技术分享
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论