简体   繁体   中英

How to reach element with this keyword in children parameter methods?

I have an object like this

function myObject(){
    this.$domElement = $('#apple');
    this.name = 'apple';
    this.color = 'green';
    this.price = '200';

    this.show = function(){
       this.$domElement.show()
    }
}

Now I want to add a new method to this object like this

this.setCss = {
    position : function(){
        //...
    },

    opacity : function(){
        //...
    },

    border : function(){
        //...
    }
}

Now, my question : How can I reach my object again with this keyword.

The final code I am expecting is something like this. If possible...

function myObject(){
    this.$domElement = $('#apple');
    this.name = 'apple';
    this.color = 'green';
    this.price = '200';
    this.show = function(){
       this.$domElement.show()
    }
    this.setCss = {
        position : function(){
        //...this.$domElement.css({top:10,left:20})
        },
        opacity : function(){
        //...this.$domElement.css({opacity:.5})
        },
        border : function(){
        //...this.$domElement.css({border:'1px solid red'})
        }
    }
}

try this

 function myObject(){
   //init
   var me = this;

    this.$domElement = $('#apple');
    this.name = 'apple';
    this.color = 'green';
    this.price = '200';

    this.show = function(){
       //use
       me.$domElement.show()
    }
}

var obj = new myObject();
obj.show();

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