Many of you have seen these two words (this and new) but what they really mean?
Let's take a standard constructor pattern example such us:
function Person(firstName, Lastname) {
this.firstName = firstName;
this.lastName = lastName;
this. fullName = function() {
return this.fristName + '' + this.lastName;
}
}
var t = new Person('T', 'P');
t.firstName; //"T"
t.fullName(); //"T", "P"
As we can see on our constructor we have the word this and It is a pointer that points to the objects that's invoking the current function
AND the new keyword does something good for us It tells to point to the object that's being instantiated.
So for example if we have
var t = new Person('T', 'P');
this pointed to T where It was used inside the Person constructor function.
And If we have
var t = Person('T', 'P');
t; //undefined
It's important to remember to use the new keyword when using this pattern.
Typically, constructors are capitalized (and instances lower-cased) to remind developers of this rule
Let's take a standard constructor pattern example such us:
function Person(firstName, Lastname) {
this.firstName = firstName;
this.lastName = lastName;
this. fullName = function() {
return this.fristName + '' + this.lastName;
}
}
var t = new Person('T', 'P');
t.firstName; //"T"
t.fullName(); //"T", "P"
As we can see on our constructor we have the word this and It is a pointer that points to the objects that's invoking the current function
AND the new keyword does something good for us It tells to point to the object that's being instantiated.
So for example if we have
var t = new Person('T', 'P');
this pointed to T where It was used inside the Person constructor function.
And If we have
var t = Person('T', 'P');
t; //undefined
It's important to remember to use the new keyword when using this pattern.
Typically, constructors are capitalized (and instances lower-cased) to remind developers of this rule
Σχόλια
Δημοσίευση σχολίου