JavaScript Object learning notes (2)-Simulation Implementation

Source: Internet
Author: User

1. instance attributes, instance methods and class attributes, and class methods

Function circle (r ){

This. redius = r; // redius attribute instance attributes, that is, each instance object of this type has the copy attribute.

}

Circle. Pi = 3.14; // P is a class attribute of the circle class and has nothing to do with the instance.

Circle. Prototype. Area = function () {return circle. Pi * This. redius * This. redius}; // area is an instance method that references the class property pi

Circle. init = function () {return new circle (1);} Init () is a class method used to create a circle with a radius of 1

Non-static attributes or functions in Java

Class attributes and methods are similar to static attributes or functions in Java.

2. class inheritance

Animals:

Function animal (){

This. type = "animal ";

}

Cat:

Function CAT (name, age ){

This. Name = Name;

This. Age = age;

}

How can we make cat inherit the animal class?

1. constructor binding mode:

Function CAT (name, age ){

Animal. Call (this, [arguments]) // arguments is the passed parameter array. this parameter is the object that calls this function. Here it is cat

This. Name = Name;

This. Age = age;

}

VaR c = new car ('Tom ', 19 );

Console. Log (C. Type );

2. Prototype inheritance mode

Cat. Prototype = new animal (); // reinitialize the original prototype of cat.

Cat. Prototype. constuctor=CAT; // The original prototype has been assigned a new value,PrototypeConstructor does not exist. Therefore, you need to re-specify the constructor value. Here is cat,
Otherwise there is a problem with the inheritance chain.

VaR c = new car ('Tom ', 19 );

Console. Log (C. Type );

In short, we should observe one point in programming if the value of O. prototype is re-assigned:

O. Prototype = {};

Next, assign a value to O. Prototype. constructor:

O. Prototype. constructor = O;

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.