javascript - 使用“this”创建构造函数,而不是简单地返回一个对象
问题描述
我的单词知识可能不足以自己在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();
有人介意解释或指导我正确的方向吗?
解决方案
this
使用 instanciable 函数的原型,而简单对象在原型链中有另一个原型。它没有自己的实例化函数原型。
您可以向原型添加新方法并观察差异。
// 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());
推荐阅读
- jstl - 在 JSTL 标签中通过 pageContext 访问请求对象
- pytorch - 将二维卷积核应用于 Pytorch 中的每个通道?
- python - 如何将python程序转换为pyspark
- cakephp - CakePHP 路由不接收参数
- python - 如何在 python/pandas 中过滤大数据框中的联合数据?
- python - 将烧瓶应用程序部署到heroku服务器后出现找不到模块错误
- python - 尝试运行 docplex 示例时出现 BrokenProcessPool 错误
- html -
屏幕缩小后隐藏 - apache-spark - SparkLauncher 独立集群模式
- socket.io - NestJS + Socket.io:没有收到消息