does javascript functions are shared across all objects? -
does javascript functions are shared across all objects? -
so code
ob1 = { m: function(){ alert(this); } } ob2.m = ob1.m;
and because think functions stored 1 time in memory in case
yes, code, both ob1
, ob2
have reference same function m
. if phone call ob1.m()
, phone call m
this
referring ob1
. if phone call obj2.m()
, phone call m
this
referring ob2
. there one re-create of function, , have multiple references function. in javascript, functions real objects, other object. (this not true of many other programming languages.)
you can this:
function m() { } var ob1 = {m: m}; var ob2 = {m: m};
again share function.
or this:
function myobject() { } myobject.prototype.m = function() { }; var ob1 = new myobject(); var ob2 = new myobject();
again share function, because both receive myobject.prototype
underlying prototype when they're created via new myobject
, , prototype has reference function.
similarly (in es5-enabled environment):
var myproto = { m: function() { } }; var ob1 = object.create(myproto); var ob2 = object.create(myproto);
the object 1 time again end sharing prototype, , prototype has m
function.
javascript function
Comments
Post a Comment