1
<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 类中调用静态方法时,它会完美地打印输出。
4

2 回答 2

4

如果要从构造函数中调用方法,则需要创建一个匿名实例:

(new Kevin).getKevin(); // or new Kevin().getKevin()
于 2012-12-29T23:55:05.590 回答
2

你得到undefined是因为原型没有“名称”属性。另请注意,您对“getStaticJohn()”的调用实际上并不能“完美运行”——它用大写的“J”警告“John”,因为它正在访问函数对象“John”的“name”属性。

当您通过表单的表达式调用方法时,函数内部的something.functionNamethis将始终是 的值something。因此,当你打电话

John.prototype.getJohn();

this“getJohn()”函数内部的值将是John.prototype,而不是由“John()”构造函数构造的任何实例。

如果你添加这个:

John.prototype.name = "John's prototype";

那么您的呼叫John.prototype.getJohn()将提醒除undefined.

于 2012-12-29T23:55:44.220 回答