2

I have a class like this

App.Person = Ember.Object.extend({
  say: function(thing) {
    alert(thing);
  }
});

I wish to add something to the method say , so that the method becomes

App.Person = Ember.Object.extend({
  say: function(thing) {
    alert(thing);
    alert("Thing is said above! ");
  }
});

So that

var person = App.Person.create();
person.say("Hello");   

Output is Hello Thing is said above! .

I have tried to reopen the class and define the method again like

App.Person.reopen({
  say: function(thing) {
    alert("Thing is said above! ");
  }
});

But then i am left only with Thing is said above! . Is there a way to "extend" a method? or perform anything similar to achieve this?

also explain how to achieve the same to extend a jquery method ? , like i have jquery method binded to an DOM element and i want to extend that to add more code

Abhishek Gupta
  • 1,297
  • 13
  • 28

2 Answers2

2

I think yes. Either you call the super function into the inherited function :

// Super class
function Person() {
     this.text = "Hello";   
}
Person.prototype.say = function () {
     alert(this.text);   
}

// Inherited class
function TalkativePerson() {
    Person.apply(this); // Call to the super constructor 
    this.extendedText = "How are you ?";
}
TalkativePerson.prototype = Object.create(Person.prototype); // Inheritance
TalkativePerson.prototype.constructor = TalkativePerson;
TalkativePerson.prototype.say = function () { // Here you redefine your method
    Person.prototype.say.call(this);//And then you call the super method
    // Add some stuff here like this :
    alert(this.extendedText);
}

var person = new TalkativePerson();
person.say();

Or you can (in your example) directly change the value of the text like this :

function TalkativePerson2() {
    this.text += ". How are you ?";
}
TalkativePerson2.prototype = new Person();

Here is a JSFiddle where you can test it.

Serge K.
  • 5,303
  • 1
  • 20
  • 27
  • It would be better to set prototype part of inheritance with Object.create (shim for old browsers) and re use Parent constructor by calling `Parent.call(this,args);` in Child or `Person.call(this,args);` in TalkativePerson even though there are no parameters used to initialise instance members you may want to re use Person constructor in the future and worth mentioning how. More info here: http://stackoverflow.com/a/16063711/1641941 Though the OP is using Ember.js (I think) to "help" with Object definition so no way of knowing what happens there without reading the docs. – HMR Feb 10 '14 at 16:00
1

You can call this._super(); in the extended version to have it call the original method. You can see an example of that here

Adam
  • 3,148
  • 19
  • 20