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 onstring.prototype
, can use both"abc".charat(1)
,string.prototype.charat.call("abc", 1)
.but
fromcharcode
defined onstring
, can usestring.fromcharcode(65)
,"abc".fromcharcode
undefined.
Comments
Post a Comment