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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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/

2 Comments

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
ok, not sure if I understood it correctly but looks like it's something similar to stackoverflow.com/questions/1789892/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.