【发布时间】:2016-06-23 18:24:08
【问题描述】:
我是 Javascript 新手,对以下语句的结果感到困惑。你能帮助澄清每个结果背后的原因吗?如果您还可以建议资源以清楚地解释这些情况下的预期行为,我们将不胜感激。
function Person(){
this.a = function(){alert("a")};
}
Person.prototype.b = function(){alert("b")};
Person.c=function(){alert("c")};
var test = new Person();
test.a(); // works
test.b(); // works
test.prototype.b(); //error
Person.prototype.a(); // error (why?)
Person.prototype.b(); //works (why?)
Person.c(); //works
Person();
Person.a(); /* error (Person() call should have set this.a
on the Person object just like the c method,
why doesn’t it work?) */
Person.b();//error (why?)
【问题讨论】:
-
只有函数有
prototype对象,test是一个对象。a没有在Person.prototype中定义,但b是。 -
@JaredSmith 你错了,你链接的问题不涉及静态属性与实例属性。请删除您的评论
-
@frankies 他的评论确实说“可能”。更具建设性的方法可能是将差异编辑到问题本身中,以便它们明显不同。
-
@frankies 我有点同意你的观点(到我发布答案的地步),鉴于低质量的答案很吸引人,这需要 mod 的关注。
标签: javascript object prototype