Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Add functions to another ones

1 view
Skip to first unread message

Archos

unread,
Feb 18, 2012, 7:42:22 AM2/18/12
to
Is there any way for that a function can be added/embedded to a
constructor?

function hello() {console.log("hello")}
function Sum(x, y) { this.a=a; this.b=b; }

In that example I would want that function hello() can be added to
Sum()
Message has been deleted
Message has been deleted

tema

unread,
Feb 18, 2012, 9:00:11 AM2/18/12
to

Archos

unread,
Feb 18, 2012, 9:33:17 AM2/18/12
to
Thanks. Although I thought that I could be done easily using 'apply'
or a similar function.

Asen Bozhilov

unread,
Feb 18, 2012, 9:54:17 AM2/18/12
to
tema wrote:

> > function hello() {console.log("hello")}
> > function Sum(x, y) { this.a=a; this.b=b; }
>
> > In that example I would want that function hello() can be added to
> > Sum()
>
> Here you gohttp://jsfiddle.net/agentcooper/qLMUz/

In first place it would be nice if the next time you post your code to
be directly here. It is definitely easier to quote different parts of
your code if it is in messages. Of course you could post here and post
link in jsfiddle. Also if jsfiddle removes your code the archive of
the group will store a broken link. In the last place not everyone is
on the web in newsgroup like that.

Such a design is better to avoid. I would use wrapper or subclassing
`Sum' instead of overwriting the constructor. Your approach after
overwriting the `Sum' with new function If I would like to extend the
`Sum.prototype', I would have a big problem. The `Sum' is not longer
constructor, it is factory for overwritten `Sum'.

Sum.prototype.missedLogic = function () {
console.log('Missed logic');
};

var h = new Sum(2, 3);
h.missedLogic(); //TypeError

If you and the author want real overwritten constructor, you could
use:

function hello() {console.log("hello")}
function Sum(x, y) { this.a=x; this.b=y; }


Sum = (function () {
var _Sum = Sum;
function SumWrapper() {
_Sum.apply(this, arguments);
hello();
}
SumWrapper.prototype = new _Sum;
return SumWrapper;
})();


John G Harris

unread,
Feb 18, 2012, 10:48:41 AM2/18/12
to
Have you realised that you've been asking some very peculiar questions.
Have you spent some time working out what you want to do, without
worrying about how to do it ?

If you have, have you understood the way prototypes work and how they
can help you ?

John
--
John Harris
0 new messages