箭頭函數、沒有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; // 傳回該對象。
};