我有一个像这样的对象
function myObject(){
this.$domElement = $('#apple');
this.name = 'apple';
this.color = 'green';
this.price = '200';
this.show = function(){
this.$domElement.show()
}
}
现在我想为这个对象添加一个新方法,就像这样
this.setCss = {
position : function(){
//...
},
opacity : function(){
//...
},
border : function(){
//...
}
}
现在,我的问题是:如何使用this
关键字再次访问我的对象。
我期待的最终代码是这样的。如果可能......
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'})
}
}
}
答案 0 :(得分:4)
试试这个
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();