methods as properties of an object in javascript -
i need create javascript function private variable has setter , getter methods. tried:
function createsecretholder(secret) { this._secret = secret; var getsecret = function(){ homecoming this._secret; } var setsecret = function(secret){ this._secret = secret; } } and version with:
this.getsecret = function()... and
this.sesecret = function()... it not passing test suite on code wars. like
var obj = createsecretholder(secret); obj.getsecret(); obj.setsecret(newsecret); and others hidden. error typeerror: cannot read property 'getsecret' of undefined , cannot phone call method setsecret
createsecretholder() doesn't return value createsecretholder(secret) returns undefined.
so var obj = createsecretholder(secret); sets obj undefined. hence error "cannot read property 'getsecret' of undefined" when seek access obj.getsecret().
even if returned object, have declared getsecret using var within function. variables described way scoped function. when seek access outside function, in obj.getsecret(), won't work.
you seem misunderstand how this works. not create private variable.
there number of ways this. here's one:
function createsecretholder(mysecret) { var secret = mysecret; homecoming { getsecret: function(){ homecoming secret; }, setsecret: function (mysecret){ secret = mysecret; } }; } javascript object
No comments:
Post a Comment