new 運算符 建立一個用戶定義的對象類型的實例或具備構造函數的內置對象的實例。
比較好奇new
運算符的原理,瞭解了下,分享給你們。javascript
看一下MDN
上的簡單🌰:java
function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } var rand = new Person("Rand McNally", 33, "M");
這樣rand
就是Person的實例了。長這樣:函數
本身寫一個New()
方法,如何達到這種效果?四行代碼...this
function New (constructor, ...args) { const obj = {}; obj.__proto__ = constructor.prototype; constructor.call(obj, ...args); return obj; }
testspa