Home > Web Front-end > JS Tutorial > body text

How to implement the new function in js? How to use new in js

不言
Release: 2018-08-20 14:45:05
Original
2736 people have browsed it

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!