js--using constructor functions to create new objects and operations

Source: Internet
Author: User

By invoking the function with the new operator to reach the object this is worth the purpose, the constructor returns the object it created to us.

Directly on the code

To create a constructor function

function Gadget (name, color) {

THIS.name = name;//Add Property

This.color = color;

This.whatareyou = function () {//Add method

return This.color + "" + this.name;

}

}

Another way to add properties and methods, through the prototype property of the constructor function, is to add

Gadget.prototype.price = 100;//Prototype Properties

Gadget.prototype.rating = 3;

Gadget.prototype.getInfo = function () {

Return this.price+ "" +this.rating;

}

/* Shorthand

Gadget.prototype = {

PRICE:100,

Rating = 3,

GetInfo = function () {

return This.price + "" +this.rating;

}

}

*/

To create a new object using the constructor

var newtoy = new Gadget (' webcam ', ' black ');

newtoy.name;//

---->>webcam

The object is passed by reference, that is, the object entity created does not have a copy of its own prototype, and the value passing produces a copy

Gadget.prototype.get = function (what) {

return This[what];

}

Newtoy.name

If the name attribute exists in the properties and prototypes of the object itself, the property of the object itself takes precedence over the properties of the prototype

The Name property in the prototype is used when you delete the (delete newtoy.name) object property

js--using constructor functions to create new objects and operations

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.