javascript constructor function not giving correct result -
i newbie js. trying use constructor function create object. here code
function player(name,age,rank) { this.name=name; this.age=age; this.rank=rank; this.sayeverything=function() { return "the name of player " + this.name + "the age " + this.age + "the rank " + this.rank; }
now adding new property this
player.matchready=true;
now create object this
var kaka=new player("kaka",22,3,false);
and when write this
document.write('kaka match ready-->' + kaka.matchready);
it gives me output kaka match ready-->undefined
why giving me undefined?? haven't added new property correctly??please tell me. thanks.
instead of player.matchready=true;
do, player.prototype.matchready = true;
this way players have match ready default on true;
also might want put function prototype.
player.prototype.sayeverything=function() { return "the name of player " + this.name + "the age " + this.age + "the rank " + this.rank; }
you can regard prototype scaffolding on outline properties , functions object should have when it's instantiated. these default values same objects.
when add functions within functions these functions duplicated in memory when instantiate new object.
when possible , when there no need scoping, try add generic functions sayeverything()
(please rename tostring()
keep in line convention) prototype.
that way player objects can use same function. more memory efficient.
Comments
Post a Comment