I tried to console variable fullName after function run ,but it doesn't changed value ,just console default value Not Set
,why was that?
function Test() {
this.clientData = {
fullName : "Not Set",
setUserName: function (firstName, lastName) {
this.fullName = firstName + " " + lastName;
},
getUserInput2: function (firstName, lastName, callback) {
callback(firstName, lastName);
}
};
this.getUserInput1 = function (firstName, lastName, callback) {
callback(firstName, lastName);
};
}
var test = new Test();
test.getUserInput1("A1", "B1", test.clientData.setUserName);
console.log("test.clientData.fullName : " + test.clientData.fullName);//Not Set
//expected => A1 B1
test.clientData.getUserInput2("A2", "B2", test.clientData.setUserName);
console.log("test.clientData.fullName : " + test.clientData.fullName);//Not Set
//expected => A2 B2
This is working. you can do this without using bind() function. you just need to store Test object in variable.
function Test() {
var t = this
this.clientData = {
fullName : "Not Set",
setUserName: function (firstName, lastName) {
t.clientData.fullName = firstName + " " + lastName;
},
getUserInput2: function (firstName, lastName, callback) {
callback(firstName, lastName);
}
};
this.getUserInput1 = function (firstName, lastName, callback) {
callback(firstName, lastName);
};
}
var test = new Test();
test.getUserInput1("A1", "B1", test.clientData.setUserName);
console.log("test.clientData.fullName : " + test.clientData.fullName);//Not Set
//expected => A1 B1
test.clientData.getUserInput2("A2", "B2", test.clientData.setUserName);
console.log("test.clientData.fullName : " + test.clientData.fullName);//Not Set
It is because when the callbacks are called, the context(this
) value of the callback is not the clientData
object.
You can set the callback manualy using Function.bind()
function Test() {
this.clientData = {
fullName: "Not Set",
setUserName: function(firstName, lastName) {
this.fullName = firstName + " " + lastName;
},
getUserInput2: function(firstName, lastName, callback) {
callback(firstName, lastName);
}
};
this.getUserInput1 = function(firstName, lastName, callback) {
callback(firstName, lastName);
};
}
var test = new Test();
var userInput = new test.getUserInput1("A1", "B1", test.clientData.setUserName.bind(test.clientData));
snippet.log("test.clientData.fullName : " + test.clientData.fullName); //Not Set
//expected => A1 B1
test.clientData.getUserInput2("A2", "B2", test.clientData.setUserName.bind(test.clientData));
snippet.log("test.clientData.fullName : " + test.clientData.fullName); //Not Set
//expected => A2 B2
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With