javascript - Modifying a field on a prototype from a child object -


this problem of cleanliness.

i'm using prototypes implement basic inheritance keep code dry, have few prototypes intents , purposes abstract (it not expected ever instantiated outside of being set prototypes other objects) , contain code "child" objects call. problem functions in prototype rely on of prototype's fields. updating field on child object not modify prototype's field. want avoid calling

childobject.prototype.field = foo; 

as gets messy deeper inheritance goes.

below i've pasted example explains i'm trying do. can see running on jsfiddle here.

//prints once. function printer(text) {     this.text = text || "";     this.print = function () {         alert(text);     }; }  //prints set number of times function annoyingprinter(text, count) {     this.prototype = new printer(text);     this.count = count || 1;      this.print = function () {         (var = 0; < this.count; i++) {             this.prototype.print();         }     }; }  function dostuff() {     var annoyer = new annoyingprinter("hello world!", 2);     annoyer.print();     //now want change text without having dig down prototype     (particularly if ever want extend annoyingprinter too)     annoyer.text = "goodbye world!";     annoyer.print(); }  //expected outcome: //hello world! //hello world! //goodbye world! //goodbye world!   //actual outcome: //hello world! //hello world! //hello world! //hello world! dostuff(); 

this typical pattern prototypal inheritance.

function printer(text) {     this.text = text || ""; } printer.prototype.print = function() {     alert(this.text); }  function annoyingprinter(text, count) {     printer.call(this, text);     this.count = count || 1; } annoyingprinter.prototype = object.create(printer.prototype);  annoyingprinter.prototype.printall = function() {     (var = 0; < this.count; i++) {         this.print();     } } 

so dostuff() can go ahead , create new annoyingprinter, , call print().

function dostuff() {     var annoyer = new annoyingprinter("hello world!", 2);     annoyer.printall();   // "hello world!" "hello world!"     annoyer.text = "goodbye world!";     annoyer.printall();   // "goodbye world!" "goodbye world!" } 

demo: http://jsfiddle.net/dhbge/

i had change 2 constructors had different method names. if gave annoyingprinter .print() method, shadow 1 printer.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -