0

私の場合(「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/ (同じコードをオンラインで試してください) </p>

ありがとう

4

2 に答える 2

4

問題は、 のプロトタイプを割り当てずChild、代わりにのインスタンスを指すプロパティprototypeを のインスタンスに作成したことです。ChildParent

代わりに、これを行います

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

同様の答えが役立つかもしれません

于 2012-05-28T00:26:04.640 に答える
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'

この場合、宣言よりも関数式を使用する唯一の理由は、他のロジックに基づいてコンストラクターを動的に作成する場合です。

于 2012-05-28T02:42:15.900 に答える