Home  >  Article  >  Web Front-end  >  What did you do after new in js?

What did you do after new in js?

一个新手
一个新手Original
2017-09-25 10:51:472316browse

(1) Create a new object;
(2) Assign the scope of the constructor to the new object (so this points to the new object);
(3) Execute the code in the constructor (Add attributes to this new object);
(4) Return the new object.

var a=new A();
1. The constructor has an attribute called prototype, here is A.prototype. This object has an attribute constructor by default, and its value is the constructor A. .

2.javascript first creates an empty object and calls it a temporary object. It inherits all the properties of A.prototype.

3. When A() starts executing, set A's this to point to this temporary object, and then continue to execute function A.

4. If there is no return statement, or a statement that returns an object, then the temporary object is returned, otherwise the object we return is returned.


Use native JS to implement the new method

function New(f) {
    return function () {
        var o = {"__proto__": f.prototype};
        f.apply(o, arguments);//继承父类的属性
        return o; //返回一个Object
    }
}

The above is the detailed content of What did you do after new in js?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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