new 和call
new
js
function newFactory (context) {
// 在传入为null的情况下 this 指向window
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); // 构造name 小明
this.name = name;
this.age = age;
this.sex = sex;
};
Person.prototype.habit = function () {
console.warn('prototype ----> i am ' + this.name); // prototype ----> i am 小明
console.warn('prototype ----> i am ' + this.age + 'years old'); // prototype ----> i am 18years old
console.warn('prototype ----> sex ' + this.sex); // prototype ----> sex 男
return '1'
}
Person.prototype.info = '吃零食';
var person1 = newFactory(Person, '小明', 18, '男')
console.error('new 的模拟', person1); // new 的模拟 Person {name: '小明', age: 18, sex: '男'}
console.warn('habit', person1.habit()); // habit 1
console.warn('name', person1.name); // name 小明
console.warn('info', person1.info); // info 吃零食
call
js
/**
*
* 在javascript 中 call 一般用于改变this的指向,
&
* 但更通俗的来讲,call 的作用是为了使执行的函数能够获得原本它获取不到的变量的访问权限。
*
*/
/**
* 在实现原理上,是对希望被访问到的对象,将当前执行的函数以自身变量的形式赋予它,
&
* 执行完毕再删除这个函数对应的变量。
*/
let obj = {
value: 10
}
function bar(name, age) {
console.log('name = ' + name); // name = 木木
console.log('age = ' + age); // age = 18
console.log('value = ' + this.value); // value = 10
}
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) // 对象 { value: 10 }