箭头函数、没有prototype、没有自己的this指向、不可以使用arguments、自然不可以new。
let fun = (a, s) => {};
console.dir(fun); // --- > 从?图可以看到 箭头函数fun是没有prototype的。
let func = function(a, s) {};
console.dir(func);
箭头函数无法使用arguments,而普通函数可以使用arguments。
let fun = (a, s) => { console.log(arguments) };
console.dir(fun); // --- >没有prototype 没有自己的this指向 不可以使用arguments 不可以new
// fun(1,2) // Uncaught ReferenceError: arguments is not defined
let func = function(a, s) { console.log(arguments) };
console.dir(func);
func(1,2) // Arguments(2) [1, 2, callee: ƒ, Symbol(Symbol.iterator): ƒ]
如果要使用类似于arguments获取参数,可以使用rest参数代替。
let fun = (...arg) => { console.log(...arg) };
fun(1,2) // 1 2
let func = function(a, s) { console.log(arguments) };
func(1,2) // Arguments(2) [1, 2, callee: ƒ, Symbol(Symbol.iterator): ƒ]
new操作实质上是定义一个具有构造函数内置对象的实例。
- 创建一个javascript空对象 {};
- 将要实例化对象的原形链指向该对象原形。
- 绑定该对象为this的指向
- 返回该对象。
let New = function(fn, ...arg) {
const obj = Object.create(fn.prototype); // 创建一个对象,将要实例化对象的原形链指向该对象。
fn.call(obj, ...arg); // 将函数指向该对象。
return obj;
};
function fun1() {
this.name = '?';
}
// 打印两者
console.log(New(fun1), new fun1()); // fun1 {name: "?"} fun1 {name: "?"}
// 判断两个实例化对象是否全等。
console.log(JSON.stringify(New(fun1)) === JSON.stringify(new fun1())); // true
使用es5写?
let New = function(fn, ...arg) {
const obj = {}; // 创建一个javascript空对象 {};
obj.__proto__ = fn.prototype; // 将要实例化对象的原形链指向该对象原形。
fn.call(obj, ...arg); // 绑定该对象为this的指向
return obj; // 返回该对象。
};