In-depth analysis of constructor in JavaScript

Source: Internet
Author: User

In-depth analysis of constructor in JavaScript

Definition and usage

The constructor attribute returns a reference to the array function that creates this object.

Syntax

Object. constructor

Constructor, constructor. We are familiar with this name. constructor always points to the constructor that creates the current object.

Note that each function has a prototype attribute. This prototype constructor points to this function. When we modify the prototype of this function, an exception occurs. For example

function Person(name,age){this.name = name;this.age = age;}Person.prototype.getAge = function(){return this.age;}Person.prototype.getName = function(){return this.name;}var p = new Person("Nicholas",18);console.log(p.constructor); //Person(name, age)console.log(p.getAge()); //18console.log(p.getName()); //Nicholas 

But if so:

function Person(name,age){this.name = name;this.age = age;}Person.prototype = {getName:function(){return this.name;},getAge:function(){return this.age;}}var p = new Person("Nicholas",18);console.log(p.constructor); //Object()console.log(p.getAge()); //18console.log(p.getName()); //Nicholas 

The constructor is changed.

The reason is that prototype itself is also an object, and the above Code is equivalent

Person.prototype = new Object({getName:function(){return this.name;},getAge:function(){return this.age;}}); 

Because constructor always points to the constructor that creates the current Object, it is not difficult to understand that the above Code p. constructor outputs the Object.

What should I do if the constructor After prototype modification still wants to point it to Person? Simple: assign a value to Person. prototype. constructor:

Person.prototype = {constructor:Person,getName:function(){return this.name;},getAge:function(){return this.age;}}

The above is the constructor in JavaScript, which I want to help you!

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.