当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Why we return this in getter and setter function?

问题描述:

sap.designstudio.sdk.DataBuffer.subclass("com.sap.sample.jsondatasource.JsonDataSource", function() {

var that = this;

var _hasHeaderRow = false;

var _hasHeaderColumn = false;

var _csvfile;

this.init = function() {

this.defineDimensions([{

key: "cols",

text: "City",

"axis": "COLUMNS",

"axis_index": 0

}, {

key: "rows",

text: "Date",

"axis": "ROWS",

"axis_index": 0

}], {

key: "measures",

text: "Measures",

containsMeasures: true,

members: [{

"key": "measure",

"text": "Temprature",

"scalingFactor": 2,

"formatString": "0.00 EUR;-0.00 EUR"

}]

});

};

this.csvfile = function(value) {

if (value === undefined) {

return _csvfile;

} else {

_csvfile = value;

return this; **//why we using this here?**

}

};

this.hasHeaderRow = function(value) {

if (value === undefined) {

return _hasHeaderRow;

} else {

_hasHeaderRow = value;

return this; **//why we using this here?**

}

};

this.hasHeaderColumn = function(value) {

if (value === undefined) {

return _hasHeaderColumn;

} else {

_hasHeaderColumn = value;

return this; **//why we using this here?**

}

};

this.afterUpdate = function() {

//

}

});

I have a doubt on this getter and setter. why we are using this here? what's the purpose instead we can return value right? Please anybody explain clearly. I have updated the entire code. Any suggestion now?

网友答案:

This is an example of a "fluent interface".

What's this? For example, if you have a an object of the foo class and every method of this class returns the foo instance, you could write

fooInst.do().some().thing()

By the way, many of the jQuery methods are implemented for usage as fluent interface, so this is quite a familiar concept to JS developers.

In the code example, most methods return the instance only if a value has been passed. In this case, the method can be used either as setter or as getter.

This is also similar to what jQuery does with several methods, for example:

var foo = $('#elem').attr('class'); // returns element's class, CANNOT be chained
$('#elem').attr('class', 'foo'); // sets class + returns instance, CAN be chained
分享给朋友:
您可能感兴趣的文章:
随机阅读: