Javascript: Извикване на дъщерна функция от родителска (супер?) функция.

И двете родителски функции се заместват от дъщерен. две в детето се обажда на родителя две. обаче очаквах, че на ниво родител извикването на един ще извика метода на детето. Има ли концепция, която пропускам?

Благодаря ви предварително!

http://jsfiddle.net/9mbGN/

function parent(){}

parent.prototype.one = function(){
    $('body').append("Parent: one <br/>");
}

parent.prototype.two = function(){
    this.one();
    $('body').append("Parent: two <br/>");
}


function child(){}

child.prototype = new parent();
child.prototype.constructor = child;

child.prototype.one = function(){ //should this function not be called? 
    $('body').append('Child: one <br />');
}

child.prototype.two = function(){
    $('body').append('Child: do some child stuff here and call parent: <br />');
    parent.prototype.two();    
}



var k = new child();
k.two();

person alotofquestions    schedule 26.09.2013    source източник
comment
this.one() се обажда на parent.prototype.one() в two() на вашето дете, защото this е parent.prototype   -  person Joe Simmons    schedule 26.09.2013
comment
Има ли някакъв начин да се извика child.prototype.one?   -  person alotofquestions    schedule 26.09.2013
comment
Просто се обадете на child.prototype.one()? Не съм сигурен какво всъщност се опитвате да направите. За какво е всичко това?   -  person Joe Simmons    schedule 26.09.2013
comment
но това не нарушава ли целта на наследяването?   -  person alotofquestions    schedule 26.09.2013
comment
Защо не просто parent.prototype.two.call(this)?   -  person slebetman    schedule 26.09.2013
comment
Да, точно това търсех. Благодаря ти!   -  person alotofquestions    schedule 26.09.2013
comment
@JoeSimmons Това не е вярно, this.one е последната стойност на one при this верига от прототипи, а това е child.prototype.one. this` е обект от прототипите child.prototype от прототипите parent.prototype   -  person A. Matías Quezada    schedule 27.09.2013
comment
@A.MatíasQuezada: Не мога да те разбера.   -  person Joe Simmons    schedule 27.09.2013
comment
@JoeSimmons ти каза, че this.one() се обажда на parent.prototype.one при детето two(), защото this е parent.prototype. Това не е вярно, this е обект от прототипите child.prototype, така че this.one препраща към child.prototype.one   -  person A. Matías Quezada    schedule 28.09.2013
comment
Когато наречете parent.prototype.two() 'това' ще бъде parent.prototype   -  person Joe Simmons    schedule 29.09.2013
comment
Моя грешка, прав си, извинявай :P   -  person A. Matías Quezada    schedule 30.09.2013


Отговори (3)


По-оптималният начин е почти като да го правите, но извиквате родителския метод над this:

child.prototype.two = function(arg1, arg2) {
  parent.prototype.two.call(this, arg1, arg2);
};

Но ви препоръчвам да използвате персонализирана функция за разширяване, можете да използвате extend от jsbase

Ако използвате ECMAScript 5 getters/setters (ако не използвате само първия), може да предпочетете да използвате този на тази същност

И двете могат да се използват по същия начин въз основа на идеята на Дийн Едуард:

var Animal = extend(Object, {

  constructor: function(name) {
    // Invoke Object's constructor
    this.base();

    this.name = name;

    // Log creation
    console.log('New animal named ' + name);
  },

  // Abstract
  makeSound: function() {
    console.log(this.name + ' is going to make a sound :)');
  },

});

var Dog = Animal.extend({

  constructor: function(name) {
    // Invoke Animals's constructor
    this.base(name);

    // Log creation
    console.log('Dog instanciation');
  },

  bark: function() {
    console.log('WOF!!!');
  },

  makeSound: function() {
    this.base();
    this.bark();
  }
});

var pet = new Dog('buddy');
// New animal named buddy
// Dog instanciation
pet.makeSound();
// buddy is going to make a sound :)
// WOF!!!

Във вашия случай може да бъде:

var parent = extend(Object, {
  one: function() {
    $('body').append("Parent: one <br/>");
  },
  two: function() {
    this.one();
    $('body').append("Parent: two <br/>");
  }
});

var child = parent.extend({
  one: function() {
    $('body').append('Child: one <br />');
  },
  two: function() {
    $('body').append('Child: do some child stuff here and call parent: <br />');
    this.base();
  }
});
person A. Matías Quezada    schedule 26.09.2013

Е, разбирам какво искате... дефинирайте функционирането си по следния начин:

child.prototype.two = (function(){
if(child.prototype.two){
   var tmp = child.prototype.two;
   return function(){
   $('body').append('Child: do some child stuff here and call parent: <br />');   
   tmp.apply(this,arguments);
   };
  }
})()

Можете да добавите друго условие за връщане на функция, ако няма същата функция, дефинирана в прототипа.

person grape_mao    schedule 26.09.2013

Отговорено от slebetman:

parent.prototype.two.call(this)

Вместо директно извикване на функцията две на родителя.

person alotofquestions    schedule 26.09.2013