0

I'm working on a big project and decided against prototyping for inheritance (I wanted more control over var and this.* access).

Anyways, I have classes that look like this:

FirstScene.prototyp

FirstScene.prototype = Object.create(_SceneCanvas.prototype)
FirstScene.prototype.constructor = FirstScene

function FirstScene(){
     var arguments = [/*args*/]
     _SceneCanvas.apply(this, arguments)



     this.bar = function(){ /*do other stuff*/ }
}

If I was in foo() or bar() and wanted to call the parent method, how would I go about doing that? I tried some code that looked like _SceneCanvas.prototype.foo.call(params) to no avail.

Thanks!

4
  • The concept "parent method" doesn't really apply for "foo"; it's a local function in the constructor. Commented Aug 17, 2015 at 15:27
  • 1
    Also I don't understand what you mean by saying you decided against prototyping for inheritance, but then you go on to post code that uses prototype inheritance. Commented Aug 17, 2015 at 15:28
  • @Pointy my functions are not in the form of FirstScene.prototype.foo = function() Am I missing something? Commented Aug 17, 2015 at 15:36
  • Yes, that's just one way of putting properties on a prototype. You're still using prototype inheritance. Commented Aug 17, 2015 at 15:46

1 Answer 1

3

In JavaScript the common practice is to get a reference to the old function and call it from within the new function.

var bar = this.bar;
this.bar = function () {
  bar.call(this);
  // ...
};

Please check out this fiddle to see it in action.

Sign up to request clarification or add additional context in comments.

3 Comments

... probably bar.call(this) to make sure there's a context.
So why does this.bar() call the parent method instead of the immediate one? (Also, your solution works. Thanks!)
It is interpreted sequentially. When bar is assigned this.bar, this.bar is the parent's bar function. The next line then overwrites this.bar to be a new function. If you move var bar = this.bar; to after you overwrite it, you'll get the new function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.