使用原型调用方法

时间:2012-12-29 23:53:55

标签: javascript

<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>
  1. 为什么我在打电话的两种情况下都得到undefined 使用原型的方法。
  2. 当我尝试在John类中调用静态方法时,它会打印出来 输出完美。

2 个答案:

答案 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以外的其他内容。