Reputation: 24621
I have simple example:
function File(name) {
this.name = name
this.text = null
}
File.prototype = {
read: function() {
fs.readFile(this.name, function (err, data) {
}
},
getContent: function() {
return this.text
}
}
var myfile = new File('my_file')
watch.createMonitor('my_file_dir', function (monitor) {
monitor.files['my_file']
monitor.on("change", function (f, stat) {
myfile.read()
}
})
main program....:
myfile.getContent() ...
I want to add file contents in this.text variable. How to do it ?
Upvotes: 2
Views: 170
Reputation: 1089
Create local variable and store there 'this'
read: function() { var _file = this; fs.readFile(this.name, function (err, data) { ... _file.text = data; ... }); },
Bind 'this' to inner function: read: function() {
fs.readFile(this.name, function (err, data) {
...
this.text = data;
...
}.bind(this)
},
Note: It's insufficiently to store data to this.text: if you read something asynchronously in yur class, you need to provide callbacks to let other objects know that you got some data in yourFile.text
Upvotes: 5
Reputation: 159105
There's a couple things you can do:
Create a scoped version of this
:
File.prototype = {
read: function() {
var self = this;
fs.readFile(this.name, function (err, data) {
self.text += data;
});
}
};
Bind the function to the current value of this
:
File.prototype = {
read: function() {
fs.readFile(this.name, function (err, data) {
this.text += data;
}.bind(this));
}
};
Upvotes: 0
Reputation: 6623
You could save a reference to this
outside the closure and reference it from within:
File.prototype = {
read: function() {
var self = this;
fs.readFile(this.name, function (err, data) {
self.text = data;
});
},
getContent: function() {
return this.text
}
}
Upvotes: 4