0

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.

Kritner
  • 13,557
  • 10
  • 46
  • 72

2 Answers2

1

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.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

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/

Anurag Sinha
  • 1,014
  • 10
  • 17
  • I don't want that. I want to have Object.newparam in place of Object.init().newparam But I don't want to set its value manually using `newparam: this.init().newparam` – Soul Reaper Dec 24 '16 at 14:27
  • ok, not sure if I understood it correctly but looks like it's something similar to http://stackoverflow.com/questions/1789892/access-parent-object-in-javascript – Anurag Sinha Dec 24 '16 at 18:01