On the basic knowledge of constructor_ in JavaScript

Source: Internet
Author: User

constructor, constructors, we are not unfamiliar with this name,constructor always point to the constructor that created the current object.

One thing to note here is that each function has a prototype attribute, and this prototype constructor points to the function, which is unexpected when we modify the prototype of this function. Such as

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",);
Console.log (P.constructor); Person (name, age)
Console.log (P.getage ());//18
Console.log (P.getname ());//nicholas

But if this is the case:

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",);
Console.log (P.constructor); Object ()
Console.log (P.getage ());//18
Console.log (P.getname ());//nicholas

The result constructor changed.

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

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 Output is object.

What about the constructor that changed the prototype and wanted it to point to person? Simply, assign a value directly to the Person.prototype.constructor:

Person.prototype = {
  Constructor:person,
  getname:function () {return
    this.name;
  },
  getage: function () {return
    this.age;
  }
}

This article on the constructor of JavaScript is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

Related Article

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.