Javascript 使用原型调用方法 var=function(){ this.name='kevin' } Kevin.prototype.getKevin=function(){ 警报(此名称); } prototype.getKevin(); 函数John(){ this.name='john' } John.getStaticJohn=function(){ 警报(此名称); } prototype.getJohn(); John.getStaticJohn(); 为什么我在调用时在这两种情况下都得到了未定义的 该方法使用原型 当我尝试在John类中调用静态方法时,它会打印 输出完美
如果要从构造函数调用方法,则需要创建一个匿名实例:Javascript 使用原型调用方法 var=function(){ this.name='kevin' } Kevin.prototype.getKevin=function(){ 警报(此名称); } prototype.getKevin(); 函数John(){ this.name='john' } John.getStaticJohn=function(){ 警报(此名称); } prototype.getJohn(); John.getStaticJohn(); 为什么我在调用时在这两种情况下都得到了未定义的 该方法使用原型 当我尝试在John类中调用静态方法时,它会打印 输出完美,javascript,Javascript,如果要从构造函数调用方法,则需要创建一个匿名实例: <script> var Kevin = function(){ this.name = 'kevin' } Kevin.prototype.getKevin = function(){ alert(this.name); } Kevin.prototype.getKevin(); f
<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>
如果要从构造函数调用方法,则需要创建一个匿名实例:
<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>
因为原型没有“name”属性,所以您得到了未定义的
。还请注意,对“getStaticJohn()”的调用实际上并没有“完美地工作”——它用大写字母“J”提醒“John”,因为它正在访问函数对象“John”的“name”属性
当您通过something.functionName
形式的表达式调用方法时,函数中this
的值将始终是something
的值。所以当你打电话的时候
(new Kevin).getKevin(); // or new Kevin().getKevin()
“getJohn()”函数中的this
的值将是John.prototype
,而不是“John()”构造函数构造的任何实例
如果您添加以下内容:
John.prototype.getJohn();
然后对John.prototype.getJohn()
的调用将发出除undefined
之外的警报,因为原型没有“name”属性,所以您将得到undefined
。还请注意,对“getStaticJohn()”的调用实际上并没有“完美地工作”——它用大写字母“J”提醒“John”,因为它正在访问函数对象“John”的“name”属性
当您通过something.functionName
形式的表达式调用方法时,函数中this
的值将始终是something
的值。所以当你打电话的时候
(new Kevin).getKevin(); // or new Kevin().getKevin()
“getJohn()”函数中的this
的值将是John.prototype
,而不是“John()”构造函数构造的任何实例
如果您添加以下内容:
John.prototype.getJohn();
然后对John.prototype.getJohn()
的调用将发出非未定义的对象的警报。prototype
只允许从对象外部扩展对象。调用它仍然依赖于首先定义的所述对象的实例。object.prototype
只允许从对象外部扩展对象。调用它仍然依赖于首先定义的所述对象的实例。你能给我一篇关于原型的好文章,让我完全理解这个概念吗?你能给我一篇关于原型的好文章,让我完全理解这个概念吗。