JavaScript Writing Method (4)

Source: Internet
Author: User

 

The tool functions are as follows:

View sourceprint? 01 /**

02 * $ class write tool function 3

03 * @ param {String} className

04 * @ param {Function} superClass

05 * @ param {Function} classImp

06 */

07 function $ class (className, superClass, classImp ){

08 if (superClass = "") superClass = Object;

09 var clazz = function (){

10 return function (){

11 if (typeof this. init = "function "){

12 this. init. apply (this, arguments );

13}

14 };

15 }();

16 var p = clazz. prototype = new superClass ();

17 var _ super = superClass. prototype;

18 window [className] = clazz;

19 classImp. apply (p, [_ super]);

20}

Define a Person class

View sourceprint? 01 $ class (Person, function (){

02 // Constructor

03 this. init = function (name ){

04 this. name = name;

05 };

06 // method body

07 this. getName = function (){

08 return this. name;

09 };

10 this. setName = function (name ){

11 this. name = name;

12 };

13 });

Create an object

View sourceprint? 1 var p = new Person (Jack );

2 console. log (p );

3 console. log (p. constructor = Person); // false

Use this tool to write classes. this. init method is essential. Students who have used Prototype Libraries know that the initialize method after Class. create is also essential.

Because inheritance is not considered, the second parameter superClass uses an empty string, that is, it inherits from the Object by default.

If the output is false, this tool class does not maintain the constructor attribute. There is a trade-off between each write type of the design, which depends entirely on the intent of the designer.

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.