new 和call
new
function newFactory (context) {
var context = context || window;
var obj = {};
Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
Constructor.call(obj, ...arguments);
return obj;
};
function Person (name, age, sex) {
console.log('构造name', name);
this.name = name;
this.age = age;
this.sex = sex;
};
Person.prototype.habit = function () {
console.warn('prototype ----> i am ' + this.name);
console.warn('prototype ----> i am ' + this.age + 'years old');
console.warn('prototype ----> sex ' + this.sex);
return '1'
}
Person.prototype.info = '吃零食';
var person1 = newFactory(Person, '小明', 18, '男')
console.error('new 的模拟', person1);
console.warn('habit', person1.habit());
console.warn('name', person1.name);
console.warn('info', person1.info);
call
let obj = {
value: 10
}
function bar(name, age) {
console.log('name = ' + name);
console.log('age = ' + age);
console.log('value = ' + this.value);
}
Function.prototype.xf_call = function(context) {
var context = context || window
context.fn = this
var args = []
for(var i = 1; i < arguments.length; i++) {
args.push('arguments[ ' + i + ' ]')
}
var result = eval('context.fn(' + args + ')')
delete context.fn
return result
}
bar.xf_call(obj, '木木', 18)
console.log('对象', obj)