0
What is the point of assigning a variable to a parameter in OOP?
In a constructor, why do we need to create a variable to store the parameter's value? For example: function Person(myName) { this.name = myName; console.log(name); } Can't I just directly write the following inside the function? console.log(myName) What is the purpose of creating the variable this.name?
1 ответ
+ 5
Object-oriented (or object-based) programming is based around the concept of storing data in objects, which have properties and methods. Objects are instances of their "blueprints", usually classes but which in JavaScript are either prototypes or constructor functions. What your code snippet represents is a constructor function. You aren't just printing the name, you are assigning it to the object instance. You can create multiple instances of the Person, all with different values in the "name" field, by using 'new':
var person1 = new Person('Pablo');
var person2 = new Person('Taija');
Now they are their own persons. Their names can be changed, or if there were methods inside the constructor function, they could be called.
function Person(myName) {
this.name = myName;
this.message = function(msg, sender) {
console.log("Message to " + this.name + ":\n" + msg + "\nFrom " + sender)
}
}
person1.message("An explanation of object-based JavaScript", person2.name);
// Console output:
// Message to Pablo:
// An explanation of object-based JavaScript
// From Taija