The content of this article is about how to implement the new function in js? The usage of new in js has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
To realize the function of new, we must first know what new does?
After var a = new A() in js
1. Create a Emptyhttp://www.php.cn/js-tutorial-378179.htmlObject obj{}
2. Point a’s this to obj{}
3. Point a's _proto_ to A's prototype
4. Execute A's constructor
5. Return obj
Code-level implementation:
function Test (name) { this.name = name; this.test = '????'; } Test.prototype.test2 = function () { console.log('测试原型链上的方法!'); } function _new () { let newObj = {}; let Constructor = Array.prototype.shift.call(arguments); newObj.__proto__ = Constructor.prototype; Constructor.apply(newObj,arguments); return newObj; } var t = _new(Test,'yz'); t.test2();
Related recommendations:
JS Core Series: Understanding the operating mechanism of new
What is the running process of the new operator in js
The above is the detailed content of How to implement the new function in js? How to use new in js. For more information, please follow other related articles on the PHP Chinese website!