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?