Open MJingv opened 5 years ago
function newOperator(ctor, ...args) {
if(typeof ctor !== 'function'){
throw 'newOperator function the first param must be a function';
}
let obj = Object.create(ctor.prototype);
let res = ctor.apply(obj, args);
let isObject = typeof res === 'object' && res !== null;
let isFunction = typoof res === 'function';
return isObect || isFunction ? res : obj;
};
bind、call、apply 、new 改变this最后一遍
手写bind
Function.prototype.mybind = function (ctx, ...res) { // ctx = ctx || window; ctx.foo = this; return () => { ctx.foo(res); delete ctx.foo; };
};
function sayname(arg) { console.log(this.name, '---arg---', arg); }
let obj = { name: 'jehol' };
sayname.mybind(obj, '我是参数')();
手写new【有问题】
新建一个对象 =》 挂属性 原型链继承方法 =》 return 这个对象
function Foo(...arg) { this.name = arg[0]; this.age = arg[1]; }
Foo.prototype.sayname = function () { console.log(this.name); }; Foo.prototype.sex = 'fe';
function Create(Foo, ...arg) { let obj = {}; obj.name = arg[0]; obj.proto = Foo.prototype; return obj; }
let f = Create(Foo, 'jehol');
f.sayname(); console.log(f.sex)