javascript - What is this line of Js code exactly doing? -
i learning objects in javascript , i'm using function construct object , adding method it. there's method change firstname of object, line this.changename=changename;
exactly do? if delete or alter changename function name else error occurs , nothing displayed. , deleting line of code leads error, seems it's essential code run can't figure out does.
<script> function person(firstname, lastname, age){ this.firstname=firstname; this.lastname=lastname; this.age=age; this.changename=changename; function changename(name){ this.firstname=name; } } me = new person("hazem", "khadash", 18); me.changename("bashar"); document.write(me.firstname);
as understand code, me created, changeme() function called method person.lastname rendered on screen.
thanks.
function person(firstname, lastname, age) { ... function changename(name){ this.firstname=name; } }
creates function available inside function person
. you've found, having makes me.changename(…)
not work, because function isn't accessible outside person
.
this.changename = changename
makes function accessible outside person
function can call me.changename
later.
notice it's this.changename = changename
, not this.changename = changename()
. parentheses, call function , assign output this.changename
; without parentheses, assigns reference function changename
this.changename
.
you change this, , equivalent:
function person(firstname, lastname, age) { ... this.changename = function(name){ this.firstname=name; } }
the best way write person
"class" this:
function person(firstname, lastname, age) { this.firstname = firstname; this.lastname = lastname; this.age = age; } person.prototype.changename = function changename(name){ this.firstname = name; };
Comments
Post a Comment