为什么原型JavaScript在这种情况下不起作用

why prototype javascript not works in that case

本文关键字:这种情况下 不起作用 JavaScript 原型 为什么      更新时间:2023-09-26

我的情况(为什么"test1"没有出现在警报窗口中):

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/(在线尝试相同的代码)

谢谢

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

相反,请执行此操作:

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

类似的答案可能会有所帮助

使用函数声明,您的代码会更清晰:

// 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'

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