2012-05-28 124 views
0

我的情况下,(为什么 “测试1” 没有出现在警报窗口):为什么JavaScript原型不工作在这种情况下

var Parent=function(){ 
    this.test1= function(){ 
     alert("test1"); 
    } 
} 

var Child=function(){ 
    this.prototype=new Parent(); 
} 

var test=new Child(); 
test.test1(); 

http://jsfiddle.net/c3sUM/2/(相同的代码在网上试试)

感谢

+0

请使用函数声明而不是函数表达式。这里使用表达式没有任何好处。 – RobG

回答

4

问题是您没有分配Child的原型,而是在Child的实例中创建了一个属性prototype,该实例指向Parent的实例。

instead, do this

var Child = function(){};  // create constructor 
Child.prototype = new Parent(); // assign instance of parent to constructor's 
           // prototype 

A similar answer可能有助于

+0

http://jsfiddle.net/c3sUM/3/ - 谢谢,但你的解决方案不起作用 – Yosef

+0

@Yosef对不起,我不清楚。我用演示更新了答案。 – Joseph

+0

谢谢!是否存在从Child类内部继承的方法? – Yosef

0

您的代码将更加清晰使用函数声明:

// Parent constructor 
function Parent() {} 

// Methods of Parent.prototype are inherited by 
// instances of parent 
Parent.prototype.test1 = function() { 
    alert('test 1'); 
} 

// Child constructor 
function Child(){} 

// Make Child.prototype an instance of Parent so 
// instances inherit from Child and Parent 
Child.prototype = new Parent(); 

// Instance inherits from Child (and hence Parent); 
var child = new Child(); 

child.test1(); // 'test 1' 

在这种情况下使用了声明函数表达式的唯一原因是如果你想动态创建基于其他逻辑的构造函数。

相关问题