Reputation: 34
Is There any way to set object property using object function? Eg:
var Object={
init: function(){
this.newParam=alert("ok");// This should alert ok while called Object.newParam()
}
}
Thanks in advance.
Upvotes: 0
Views: 67
Reputation: 1032
Try something like:
var Object={
init: function(){
return {
newParam :function() {
alert("ok");// This should alert ok while called Object.newParam()
}
}
}
}
console.debug(Object.init().newParam());
Note that when init() is called it returns an object. You can use that object and invoke newParam function from that - Object.init().newParam()
Fiddle at https://jsfiddle.net/krwxoumL/
Upvotes: 1
Reputation: 67207
No it wouldn't get called as per your expectation. It would get called during the time when the object is getting initialized. And obj.newParam
would have the returned value of alert("ok")
, i.e] undefined
.
You have to rewrite your code like below to achieve what you want,
var obj = {
init: function(){
this.newParam= function() {
alert("ok");// This should alert ok while called Object.newParam()
}
}
}
Also using name Object
for your variable is a riskier one when you are in the global context.
Upvotes: 1