Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic javascript prototype extension

I am trying to build a simple worker function that takes a config of properties to be set in the prototype of a class.

Assume that I declare a function that serves as a class stub:

// declaration of "constructor" to fill data members from passed object
function MyClass (config) {
    for (var key in config)
        this[key] = config[key];
}

NOTE: this itself is a hassle to do each time and I would like a design pattern for the body of this "constructor".

However, now I want to dynamically set the various prototype members of this "class" in batch as follows:

ExtendPrototype(MyClass, {
    func1 : function (arg1) {
    },

    func2 : function (arg2) {
    },

    ...
});

This way it really looks and feels like a class.

The key is the global function ExtendPrototype, which I try as follows:

function ExtendPrototype (cls, protoconfig) {
    for (var key in protoconfig)
        cls.prototype[key] = protoconfig[key];
}

My question is will this work by treating "prototype" as an object, working exactly internally, truly setting the various prototype members as if I had set the cls.prototype.myfunc = function () as several standalone statements?

Or do I have to do something complicated with "eval" in my ExtendPrototype function?

I know that existing javascript libraries do things like this, but for my own code, I'm trying to write a simple class architecture.

Andy

like image 527
Andy Nuss Avatar asked Jan 23 '26 10:01

Andy Nuss


1 Answers

This should work as expected. There's no difference between setting properties with dot notation, to setting them in bracket notation.

Here's the fiddle to prove it: http://jsfiddle.net/qrsNj/


P.S. You shouldn't have the name of random functions start with an uppercase letter. That's a convention reserved for object constructors.

like image 180
Joseph Silber Avatar answered Jan 25 '26 07:01

Joseph Silber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!