The new keyword does the following things:
Step 1: Creates a blank, plain JavaScript object;
Step 2: Links (sets the constructor of) this object to another object;
Step 3: Passes the newly created object from Step 1 as the `this` context;
Step 4: Returns this if the function doesn't return an object.
var obj = {
normal: function() {
this.privatefunction = function() {
console.log('inside privatefunction', this)
}
}
}
var norm = obj.normal() // does nothing
norm.privatefunction() // throws TypeError:
// Cannot read property 'privatefunction' of undefined
var newNorm = new obj.normal()
newNorm.privatefunction() // inside privatefunction normal {privatefunction: ƒ}
The newNorm
variable of normal function instantiated with new
keyword is able to call privatefunction
without an error because of Step 4 (Returns this
because normal
function returns undefined
)
Top comments (0)