JS Object-Oriented programming--creating objects

Source: Internet
Author: User

JavaScript sets a prototype for each object that is created, pointing to its prototype object.

When we access the properties of an object using Obj.xxx, the JavaScript engine looks for the property on the current object, and if it is not found, it is found on its prototype object, and if it is not found, it is traced back to the Object.prototype object, and finally, if it is not found, it can only return undefine D.

For example, create an array object:

var arr = [n/a];

Its prototype chain is:

Null

Array.prototype defines methods such as indexof (), Shift (), so you can call these methods directly on all the array objects.

When we create a function:

   function    foo () {            return 0;        }

The function is also an object, and its prototype chain is:

Foo ——— >function.prototype-->object.prototype-->null

Because Function.prototype defines methods such as apply (), all functions can call the Apply () method.

It is easy to think that if the prototype chain is long, then accessing an object's properties will become slower because it takes more time to find it, so be careful not to make the prototype chain too long.

constructor function

In addition to the direct use of {...} In addition to creating an object, JavaScript can also create an object using a constructor method, which is used to define a constructor first:

function Student (name) {            this. Name = name;               This function () {                alert (' hello ' +this. name+ '! ') );            }        }

This is really a normal function, but in JavaScript, you can call this function with the keyword new and return an object

   var   new Student (' xiaoming ');        Xiaoming.name; // ' Xiao Ming '        Xiaoming.hello (); // Hello, Xiaoming!

Note that if you do not write new, this is a normal function that returns undefined, but if you write new, it becomes a constructor that binds this to the newly created object and returns the this by default, that is, does not need to write the return this at the last point;

The prototype chain for the newly created Xiaoming is:

Xiaoming-->student.prototype-->object.prototype-->null

That is, Xiaoming's prototype points to the prototype of the function student, and if you create Xiaohong, Xiaojun, then the prototypes of these objects are the same as the xiaoming.

Objects created with newstudent () also derive a constructor attribute from the prototype, which points to the function student itself:

      Xiaoming.constructor = = = Student.prototype.constructor; // true        Student.prototype.constructor = = = Student; // true        Object.getprototypeof (xiaoming) = = = Student.prototype; // true        Xiaoming. instanceof Student; //

The red Arrow is the prototype chain, note that Student.protorype points to the object is Xiaoming, Xiaohong prototype object, the prototype object itself has a property constructor, point to the Student function itself.

In addition, the function student exactly has a property prototype point to Xiaoming, Xiaohong prototype object, but Xiaoming, xiaohong these objects can not prototype this property, but you can use _proto_ This non-standard brick usage to view.

Now we think Xiaoming, Xiaohong these objects "inherit" from student.

There is a small problem:

      Xiaoming.name; // ' Xiao Ming '        Xiaohong.name; // ' Little Red '        Xiaoming.hello; // Function:Student.hello ()        Xiaoming.hello; // Function:Student.hello ()        Xiaoming.hello = = = Xiaohong.hello; // false

Xiaoming and Xiaohong have different name, this is right, otherwise we can not distinguish who is who.

Xiaoming and Xiaohong's respective Hello is a function, but they are two different functions, although the function name and code are the same!

If we create a lot of objects with new Student (), the Hello function of these objects actually only needs to share the same function, which can save a lot of memory.

To let the created object share a Hello function, according to the object's property lookup principle, we just move the Hello function to Xiaoming, xiaohong the common prototype of these objects, that is, Student.prototype:

To modify the code:

function Student (name) {            this. Name = name;        }          function () {            alert (' Hello, ' +this. name+ '! ') );        }

Create a prototype-based JavaScript object with new, above.

Forgot to write new what to do?

What if a function is defined as the constructor used to create the object, but when the call forgets to write new?

In strict mode, This.name=name will error, because this binding is undefined, in non-strict mode, This.name=name does not error, because this binding is window, so inadvertently created a global variable name , and returns undefined, the result is even worse.

So call the constructor and never forget to write new. In order to differentiate between ordinary functions and constructors, by convention, the initial letter of the constructor should be capitalized, and the first letter of the normal function should be lowercase, so that some grammar checking tools such as JSLint will help you detect the missing write new.

Finally we can write a createstudent () function that encapsulates all the new operations internally, a common programming pattern like this:

  function   Student (props) { 
   
    this . Name = Props.name | | ' Anonymous '; 
    //            
     this . Grade = Props.grade | | 1; //  } Student.prototype.hello  = function () {alert ( ' Hello ', ' + function   Createstudent (props) { Span style= "COLOR: #0000ff" >return  new  Student (Props | |  {})}  
   

This createstudent () function has a few huge bit: one is not required to call with new, the second is very flexible parameters, can not pass, can also be passed:

var xiaoming = createstudent ({            name:' xiaoming '        });        Xiaoming.grade; // 1

If you create an object that has many properties, we only need to pass some of the required properties, and the rest of the properties can be used as default values. Since the parameter is an object, we do not need to memorize the order of the parameters, and if we get an object from JSON, we can create the xiaoming directly.

JS Object-Oriented programming--creating objects

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.