What happens when we create an object with the new operator?

Source: Internet
Author: User

The following code is a piece of code in JavaScript design patterns and development practices

function person (name) {
THIS.name = name;
};
Person.prototype.getName = function () {
return this.name;
};
var objectfactory = function () {
var obj = new Object (),//Cloning an empty object from Object.prototype
Constructor = [].shift.call (arguments); Gets the externally passed in constructor, this example is the person
obj.__proto__ = Constructor.prototype; Manually point the object to the correct location

var ret = constructor.apply (obj,arguments)//borrow external incoming constructor to set properties for obj

return typeof ret = = = ' object '? ret:obj;//ensure that the constructor always returns an object
}

var b = new person (' Sven ');//Use the object created by the new constructor

var a = objectfactory (person, ' Sven ');
Console.info (B.name)
Console.log (A.name); Output: Sven
Console.log (A.getname ()); Output: Sven
Console.log (object.getprototypeof (a) = = = Person.prototype); Output: True

What happens when we create an object with the new operator?

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.