i'm learning javascript. come c# background. in c#, there concept of partial classes. in other words, way split definition of class across files. there way in javascript?
currently, have directory structure this:
/ myclass.js child-folder myclassadditions.js myclass.js
function myclass() { } is there way add additional functions myclass myclassadditions.js? if so, how?
while js doesn't have formal classes, can create constructor objects can instantiated. can extend these objects or add onto them later. here's simple example:
// create constructor var myclass = function(param1) { // create instance properties here this.param1 = param1; }; // instances of class point constructors prototype myclass.prototype.printparams = function () { console.log("the value of param1 is", this.param1); }; // lets create 2 instances can see how prototype thing works var foo = new myclass("foo"); var bar = new myclass("bar"); foo.printparams(); // => value of param1 foo bar.printparams(); // => value of param1 bar foo.param1 = "oof"; foo.printparams(); // => value of param1 oof // now, lets change how printparams works. // remember, still have instances of foo , bar created. // since both point constructors prototype, // can change things later... @ time. myclass.prototype.printparams = function () { console.log("param1 said what??", this.param1); }; myclass.prototype.saynothing = function () { console.log("nothing"); }; // instances these new methods, yay prototypal inheritance foo.printparams(); // => param1 said what?? oof bar.printparams(); // => param1 said what?? bar foo.saynothing(); // => nothing bar.saynothing(); // => nothing // lets want foo have it's own saynothing method, // can define 1 on instance - not cool, doable foo.saynothing = function () { console.log("nothing @ all"); // if want cool, can call shared prototype method this.constructor.prototype.saynothing.call(this); }; // bar still going use method defined on prototype // while foo have own implementation of saynothing foo.saynothing(); // => nothing @ // => nothing bar.saynothing(); // => nothing
Comments
Post a Comment