【发布时间】:2019-06-07 09:46:27
【问题描述】:
我试图了解以下 3 个函数之间的区别。经过一天的 MDN 和其他来源,我得出了一些“结论”,我想知道是否有人可以帮助我验证它们。谢谢你:)
BLOCK #1(基于原型的构造函数示例)
function Person (name){
this.name = name;
this.greeting = function(){
alert(this.name);
};
}
var person = new Person('Bob');
BLOCK #2(另一个基于原型的构造函数示例)
function Person(name) {
this.name = name;
}
Person.prototype.greeting = function() {
alert(this.name);
}
let person = new Person("Bob");
BLOCK #3(基于原型的 ES6 类示例)
class Person {
constructor(name) {
this.name = name;
}
greeting() {
alert(this.name);
}
}
let person = new Person("Bob");
问题:
-
这三个函数将名称和问候成员添加到 Person 对象原型中。这种说法正确吗?
-
与 Block #1 和 Block #2 中的代码相比,Block #3 中的代码使用新的 ES6 类关键字并以不同的方式“在幕后”工作。 (PS。我正在写“幕后”,因为我还没有清楚地了解当我调用该函数时引擎盖下会发生什么,但目前我认为我太陌生了,无法深入研究)。
-
第 1 块和第 2 块中的代码达到相同的目标,并以相同的方式在“幕后”工作。两者代码的区别在于,在 Block #1 中,我们将
name变量和函数greeting保留在同一代码块中,而在 Block #2 中,我们将函数greeting与变量name(将greeting函数添加到Person原型,使用Person.prototype.greeting) -
在 Block #2 中使用
Person.prototype.greeting = function () {...},我们得到的结果与在 Block #1 中将this.greeting = function (...)放在this.name下面的结果相同
谢谢!
【问题讨论】:
-
块#1和块#3有什么区别?除了不同的类名以及您不调用该方法这一事实之外,我无法发现差异
-
"使用
Person.prototype.greeting = function () {...},我们可以得到与将this.greeting = function (...)放在this.name下方相同的结果" - no -
对不起,我复制粘贴了错误的代码。现在它已经修复了@CristianTraìna
-
你知道#3 仍然是“基于”原型的,对吧?
-
是的@evolutionxbox,你是对的。我为未来的读者编辑了文本
标签: javascript class ecmascript-6 prototype