<script>
var Kevin = function(){
this.name = 'kevin'
}
Kevin.prototype.getKevin = function(){
alert(this.name);
}
Kevin.prototype.getKevin();
function John(){
this.name = 'john'
}
John.getStaticJohn = function(){
alert(this.name);
}
John.prototype.getJohn();
John.getStaticJohn();
</script>
undefined
使用原型的方法。答案 0 :(得分:4)
如果要从构造函数中调用方法,则需要创建一个匿名实例:
(new Kevin).getKevin(); // or new Kevin().getKevin()
答案 1 :(得分:2)
你得到undefined
因为原型没有“名称”属性。另请注意,您对“getStaticJohn()”的调用实际上并不“完美地工作” - 它使用大写“J”警告“John”,因为它正在访问函数对象“John”的“name”属性。
当您通过something.functionName
形式的表达式调用方法时,函数内this
的值将始终为something
的值。因此,当你打电话
John.prototype.getJohn();
“getJohn()”函数中this
的值为John.prototype
,而不是“John()”构造函数构造的任何实例。
如果你添加:
John.prototype.name = "John's prototype";
然后,您对John.prototype.getJohn()
的通话会提醒undefined
以外的其他内容。