我对单词的了解可能不足以独自找到www上的解释。因此,请原谅我。
我目前正在试图弄清为什么我们在函数构造函数中使用“ this”而不是简单地返回一个对象?
例如这个JSFiddle
// Using this inside function
function Student1(first,last) {
this.firstName = first;
this.lastName = last;
this.display = function(){
return this.firstName + " " + this.lastName;
};
}
const harry = new Student1("Harry", "Potter");
document.querySelector("div").innerHTML = harry.display();
document.querySelector("div").innerHTML += "<br>";
// Returning object
function Studen2(first,last){
return {
firstName: first,
lastName: last,
display(){
return this.firstName + " " + this.lastName;
}
};
}
const ron = new Student1("Ron", "Weasley");
document.querySelector("div").innerHTML += ron.display();
有人介意向我解释或指导我正确的方向吗?
答案 0 :(得分:2)
this
使用可实例化函数的原型,而简单对象在原型链中有另一个原型。它没有自己的可实例化函数原型。
您可以在原型中添加新方法并观察差异。
// Using this inside function
function Student1(first,last) {
this.firstName = first;
this.lastName = last;
this.display = function(){
return this.firstName + " " + this.lastName;
};
}
const harry = new Student1("Harry", "Potter");
Student1.prototype.morning = function () { return 'good morning ' + this.firstName + " " + this.lastName; };
console.log(harry.morning());
// Returning object
function Studen2(first,last){
return {
firstName: first,
lastName: last,
display(){
return this.firstName + " " + this.lastName;
}
};
}
const ron = new Student1("Ron", "Weasley");
Student2.prototype.morning = function () { return 'good morning ' + this.firstName + " " + this.lastName; };
console.log(ron.morning());
答案 1 :(得分:1)
通常,您将需要在类原型上定义对象方法,这样就不必在每次创建类的新实例时都重新实例化它们,例如:
function Student1(first,last) {
this.firstName = first;
this.lastName = last;
}
Student1.prototype.display = function() {
return this.firstName + " " + this.lastName;
}
const harry = new Student1("Harry", "Potter");
document.querySelector("div").innerHTML = harry.display();
如果仅返回一个(匿名)对象,则该对象将没有原型,并且每次构造函数被调用时都必须定义该函数。
另外,在您的示例中:
harry instanceof Student1 // true
ron instanceof Student2 // false
所以您不能使用instanceof。