实现
Function.prototype.bind = function (ctx, ... argv1) {
// 保存函数
var _this = this;
ctx.from = 'obj';
// 返回一个待执行的函数
return function F(){
if(this instanceof F){
// 若是用new操作符调用,则直接用new 调用原函数,并用扩展运算符传递参数
return new _this(...argv1)
}else{
// 用apply调用第一步保存的函数,并绑定this,传递合并的参数数组
_this.apply(ctx,...argv1);
}
}
}
function Person(){
this.name="zs";
this.age=18;
this.gender="男"
console.log('Person.this:', this)
}
var obj={
hobby:"看书"
}
// 将构造函数的this绑定为obj ,此处调用上面开发的mybind方法;
var changePerson = Person.bind(obj);
// 直接调用构造函数,函数会操作obj对象,给其添加三个属性;
changePerson();
// 1、输出obj
console.log(obj);
// 用改变了this指向的构造函数,new一个实例出来
var p = new changePerson();
// 2、输出obj
console.log(p);