When you invoke the Constructor Function with new, the following happens inside the
function:
- An empty object is created and referenced by this variable, inheriting the prototype of the function.
- Properties and methods are added to the object referenced by this.
- The newly created object referenced by this is returned at the end implicitly (if no other object was returned explicitly).
/**
* @constructor
* @param{string} name
*/
var Person = function( name ) {
// 1
// var this = Object.create(Person.prototype);
// 2
// add properties and methods
this.name = name;
this.say = function( ) {
return "I am " + this.name;
};
//3
// return this;
};
var joe = new Person( "Joe" );
typeof joe === 'object'; // true
joe.constructor === Person; // true
joe instanceof Person; // true
* @constructor
* @param{string} name
*/
var Person = function( name ) {
// 1
// var this = Object.create(Person.prototype);
// 2
// add properties and methods
this.name = name;
this.say = function( ) {
return "I am " + this.name;
};
//3
// return this;
};
var joe = new Person( "Joe" );
typeof joe === 'object'; // true
joe.constructor === Person; // true
joe instanceof Person; // true
Constructor’s Return Values
When invoked with new, a constructor function always returns an object. Constructors implicitly return this, even when you don’t have a return statement in the function. But you can return any other object of your choosing.
Is it confusing?
/**
* @constructor
* @param{string} name
*/
var Person = function( name ) {
this.name = name;
return name;
}
var joe = new Person( "joe" );
typeof joe === 'object'// true
joe.name // joe
* @constructor
* @param{string} name
*/
var Person = function( name ) {
this.name = name;
return name;
}
var joe = new Person( "joe" );
typeof joe === 'object'// true
joe.name // joe
When the [[Construct]] internal method for a Function object F is called with a possibly empty list of arguments, the following steps are taken:
- Let obj be a newly created native ECMAScript object.
- Set the [[Class]] internal property of obj to "Object".
- Set the [[Extensible]] internal property of obj to true.
- Let proto be the value of calling the [[Get]] internal property of F with argument "prototype".
- Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.
- Return obj.
No comments:
Post a Comment