javascript - Using constructor function to add methods -


the classic way create constructor function like:

var obj = function(param){     this.param = param;     this.method = function(){ console.log(this.param); } } 

but why can't this:

obj.anothermethod = function(){ //some code } 

(i know obj.prototype.anothermethod).

in practical usage can't understand why use string.prototype.func instead of string.func define new method. because string constructor function , it's impossible add method it?

those different things.

if add method constructor.prototype, available on instances of constructor.

you can add methods constructor itself. however, instances won't inherit them.

for example,

  • charat method defined on string.prototype, can use both "abc".charat(1) , string.prototype.charat.call("abc", 1).

  • but fromcharcode defined on string, can use string.fromcharcode(65), "abc".fromcharcode undefined.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -