简体   繁体   中英

Setting an object's property value using object's method

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.

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") , ie] 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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM