JavaScript objects, classes, and methods

Source: Internet
Author: User
Tags ming

1. Concepts of classes and objects:

1. All things are an object, and a class is a collection of things that have the same properties and behavior methods

2. The purpose of building objects in JavaScript is to integrate all code that behaves with the same attributes to facilitate user management

3. A class is an abstraction of something that has the same characteristics and methods (behaviors), which can be understood as: An object is an instance of a class, a class is an instance of an object

2. How to create a new object:

var str = "123"; String string var str2 = new String ("123"); Object objects

3. The new object has the following two ways:

The first way var obj = new Object (); Console.log (typeof obj); Object objects//The second way var obj1 = {};console.log (typeof obj1); Object objects

4. How to add properties and methods to an object

var person1 = {    name: "Xiaoming",        age:20,    height:180,    sex: "Male",    walk:function () {        Console.log ("I Can walk! ");        return 2;}          } var _name1 = Person1.name;console.log (_name1); The result: Xiao Ming Console.log (Person1.walk ()); The result is: I can walk 2 here to note: The content added to the object: attribute and attribute values are separated by: (colon), between attributes and attributes, and (comma) separated by the properties and methods of the calling object. (point), especially in the
The last attribute cannot be appended, (comma), the system will error

5. How to add properties and methods to an object using the method of a function

var person = function (_name,_age,_height,_sex) {      var obj = new Object ();//Create a new object      obj.name = _name,      Obj.age = _age,      obj.height = _height,      obj.sex = _sex,      obj.walk = function () {            Console.log ("I can walk ");            return 2;      }      return obj; The built-in object needs to be returned as the return value of the function}var person = new Person ("xiaoming", 16,160, "male"), Console.log (Person.walk ());//output: I can walk 2person.walk ();//Output result: I can walkconsole.log (person.height); Output results: 160

6. Create an object with enough function: note: The first letter of the constructor is capitalized; The constructor's mechanism: the constructor automatically creates an empty object and then associates with this, and returns the value as the default return

function Person (_name,_age,_height) {    this.name = _name,    this.age = _age,    this.height = _height,    This.walk = function () {         Console.log ("I can Walk");         return 2;}    }    var person1 = new Person ("Xiaoming", 18,180), var person2 = new Person ("Little Red", 20,170); Console.log (person1.name);// Output: Xiao Ming Console.log (Person2.walk ());//I Can walk 2person1.walk (); I can walk

Note: Constructors: Through constructors we don't have to define properties and methods over and over again, we construct two objects by constructor: Person1,person2. Person1 and Person2 can also be called two instances of the function person.

7. Of course, the system has built-in many constructors such as String Array Object number: Two examples of simple code

var str1 = new String ("123"), Console.log (STR1);//output: string{"123"}console.log (typeof str1);//output: Objectvar str2 = New Number ("123"); Console.log (str2);//output: Number{123}console.log (typeof str2);//output is: Object visible they are all a kind of constructor, It's all created objects.

8. Prototype prototype

Prototype is used to solve the problem of excessive memory consumption, each function will be created by default assigned a prototype property, the constructor is no exception, while prototype is a pointer, he points to an object, the characteristics of the prototype prototype, There is only one copy in memory.

function Person (_name,_age,_height) {    this.name = _name,    this.age = _age,      this.height = _height,    This.walk = function () {        Console.log ("I can Walk");}    }    Person.prototype.info = function () {    console.log ("My name is:" +this.name);} Person.prototype.walk = function () {    Console.log ("I can Walk");} var person = new Person ("Xiaoming", 18,180); Console.log (Person.name); Output: Xiao Ming Person.info ();//output: My name is: Xiao Ming Person.walk ();//output: I'll walk too. This time we comment out the walk method in the constructor, Then we call the Walk Method Person.walk ();//The output is: I can walk: when an object attempts to invoke a property and method, it will go to the constructor of the object first, if the constructor of the function does not have the words will go, In the prototype for the constructor.

9. Also use prototypes as an object

function Person (_name,_age,_height) {    this.name = _name,    this.age = _age,    this.height = _height    This.walk = function () {        Console.log ("I can Walk");}    } Person.prototype = {    info:function () {              console.log ("My name is:" +this.name);           },    walk:function () {              Console.log ("I can Walk");}           } var person = new Person ("Little Red", 18,170); Console.log (person.name);//output: Little Red person.info ();//My name is: Little Red person.walk ();// I can walk and there's no difference, it's just another way to create a prototype

10. There are three main characteristics of object-oriented: encapsulation, inheritance, polymorphism, we say now inheritance, there are many ways in inheritance, first of all, call and apply method (two methods are basically the same) the root of this and apply method is to change the direction of this. However, this approach can only implement the inheritance of constructors, but it cannot implement the inheritance of prototypes.

First create a constructor function person (_name,_age,_sex) {    this.name = _name;    This.age = _age;    This.sex = _sex;} Create a prototype for the constructor Person.prototype = {    info:function () {        console.log ("My name is:" +this.name);    },    walk: function () {        Console.log ("I can Walk");}    } Create a constructor to inherit Personfunction Student (_name,_age,_sex,_height) {    person.call (this,_name,_age,_sex);//call method to inherit    this.height = _height;} var student = new Student ("Xiaoming", 18, "Male", "n"), var person = new Person ("Little Red", 16, "female"), Console.log (Student.name, Student.height);//output result: Xiao Ming 180console.log (person.name,student.age); Small red 18person.info ();//The output is: My name is: Little Red student.info ();//output is  student.info a function// Thus: Student inherits the constructor of the person, but does not inherit the person's prototype.

11. Based on the previous code, let's change the way student is inherited. Change to apply to see what effect

First create a constructor function person (_name,_age,_sex) {    this.name = _name;    This.age = _age;    This.sex = _sex;} Create a prototype for the constructor Person.prototype = {    info:function () {        console.log ("My name is:" +this.name);    },    walk: function () {        Console.log ("I can Walk");}    } Create a constructor inheritance Personfunction Student (_name,_age,_sex,_height) {    person.apply (this,[_name,_age,_sex]);// The Apply method inherits    This.height = _height;} var student = new Student ("Xiaoming", 18, "Male", "n"), var person = new Person ("Little Red", 16, "female"), Console.log (Student.name, Student.height);//output result: Xiao Ming 180console.log (person.name,student.age); Small red 18person.info ();//The output is: My name is: Little Red student.info ();//output is  student.info a function// Thus: Student inherits the constructor of the person, but does not inherit the person's prototype.

12. How to get student to inherit the person's prototype: on the issue of prototype inheritance, it may be said that we directly assign the prototype of the man to student's prototype is not OK? Well, let's take a look at this method first.

First, let's paste the previous code//Create a constructor function person (_name,_age,_sex) {this.name = _name;    This.age = _age; This.sex = _sex;}    Create a prototype for the constructor Person.prototype = {info:function () {console.log ("My name is:" +this.name);    }, Walk:function () {Console.log ("I can Walk"); }}//creates a constructor that inherits Personfunction Student (_name,_age,_sex,_height) {person.apply (this,[_name,_age,_sex]);// The Apply method Inherits This.height = _height;} The prototype of person is assigned to student's prototype Student.prototype = person.prototype;//in order to differentiate two prototypes, We're adding a method to the student prototype Student.prototype.high = function () {Console.log ("My height is:" + this.height);} var person = new Person ("Little Red", 16, "female"), var student = new Student ("Xiaoming", 18, "male", 180);//Here we only look at the inheritance of the prototype, the inheritance of the constructor is not much to say Person.info ();//output Result: My name is: Little Red student.info ();//output Result: My name is: Xiaoming Student.high ();//output Result: My height is: 180//is now visible: Student inherits the person prototype, And his own unique prototype method industry maintained//But this method also has a great disadvantage, we execute the following code Person.high ();//output Result: My height is: undefined//This is a problem, normal should be person.high not a function is correct because we do not define the high method in the person prototype, but this shows that the method exists, but there is no
Define parameters//Actually the reason is very simple, before we said the prototype here is like a pointer, when we make the assignment, change the pointer to the address, so the student and the person's prototype has changed

13. So how do we achieve the inheritance of prototypes? In prototypes, the common approach is to talk about student's prototype as an instantiated object of the person class.

First, let's paste the previous code//Create a constructor function person (_name,_age,_sex) {this.name = _name;    This.age = _age; This.sex = _sex;}    Create a prototype for the constructor Person.prototype = {info:function () {console.log ("My name is:" +this.name);    }, Walk:function () {Console.log ("I can Walk"); }}//creates a constructor that inherits Personfunction Student (_name,_age,_sex,_height) {person.apply (this,[_name,_age,_sex]);// The Apply method Inherits This.height = _height;} The prototype of student as an instantiated object of person Student.prototype = new Person ("everyday", 16, "female");//In order to differentiate two prototypes, we are adding a method to the student prototype// Prototype Creator Function 1student.prototype.high = function () {Console.log ("My height is:" + this.height);}        Prototype Creation Function 2student.prototype = {high:function () {Console.log ("My height is:" + this.height); }}var person = new Person ("Little Red", 16, "female"), var student = new Student ("Xiaoming", 18, "male", 180);//Here we look at the inheritance of prototypes, The inheritance of constructors does not say much about person.info ();//output Result: My name is: Little Red student.info ();//output Result: My name is: Xiaoming Student.high ();//output Result: My height is: 180// It is now visible: there is no problem here, we still test the person.high ();//Output result: Person.high is not afunction//See this is right//Of course this also has some other problems//before we mentioned two ways to create prototypes; the first way is no problem, now let's look at the second (shielding first)//At this time except the slightest effect of person.info () not affected; The following will prompt: Student.info is not a function: What is the reason?         In fact, the reason is very simple, is the back of the prototype to the front of the trip to cover off, so that after the inheritance we also want to add other methods to the successor in accordance with the prototype to create a function to do it

14: Prototype chain: When an object attempts to acquire a property or method, if the object's constructor is not, go back to the constructor of the prototype function to find, if the prototype is not so go to prototype object prototype to find, and eventually arrive Object.prototype

  

  

  

  

  

  

  

  

JavaScript objects, classes, and methods

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.