Method 6 of javascript writing

Source: Internet
Author: User

6. Writing Method of Prototype. js
Copy codeThe Code is as follows:
// Code in prototype. js
Var Class = {
Create: function (){
Return function (){
This. initialize. apply (this, arguments );
}
}
}
// Simplified
Function Clazz (){
Return function (){
This. initialize. apply (this, arguments );
}
}

Follow these steps to write a class,
Copy codeThe Code is as follows:
// Class name Person
Var Person = Class. create ();

// Define Person through prototype Rewriting
Person. prototype = {
Initialize: function (name ){
This. name = name;
},
GetName: function (){
Return this. name;
},
SetName: function (name ){
This. name = name;
}
}

// Create an object
Var p = new Person ("jack ");
Console. log (p. constructor = Person); // false

Initialize initializes the object (equivalent to the constructor) and writes down the methods in sequence.



If there is a problem, we can see that p. constructor = Person is false, which is a small defect of Prototype. js. The reason is that the prototype of Person is rewritten. To enable the constructor to point to the correct constructor, you only need to maintain the constructor attribute during prototype rewriting.
Copy codeThe Code is as follows:
Person. prototype = {
Constructor: Person, // note this
Initialize: function (name ){
This. name = name;
},
GetName: function (){
Return this. name;
},
SetName: function (name ){
This. name = name;
}
}

All right, p. constructor = Person is true.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.