Last active
December 14, 2015 02:49
-
-
Save warseph/5016395 to your computer and use it in GitHub Desktop.
Javascript apply/call examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Basic call - apply | |
var test = function (a, b) { | |
return a + b; | |
} | |
test(1, 2); // 3 | |
test.apply(null, [1, 2]); // 3 | |
test.call(null, 1, 2); // 3 | |
// OOP call - apply | |
var Operator = function (a, b) { | |
this.a = a; | |
this.b = b; | |
this.sum = function () { | |
return this.a + this.b; | |
}; | |
} | |
var a = new Operator(1, 2); | |
a.sum(); // 3 | |
a.sum.apply(null, [1, 2]); // null | |
a.sum.call(null, 1, 2); // null | |
a.sum.apply(a, [1, 2]); // 3 | |
a.sum.call(a, 1, 2); // 3 | |
// Functional/OOP call - apply | |
var Operator = function (a, b) { | |
this.sum = function () { | |
return a + b; | |
}; | |
} | |
var a = new Operator(1, 2); | |
a.sum(); // 3 | |
a.sum.apply(null, [1, 2]); // 3 | |
a.sum.call(null, 1, 2); // 3 | |
a.sum.apply(a, [1, 2]); // 3 | |
a.sum.call(a, 1, 2); // 3 | |
// Alternate solution for OOP call - apply | |
var Operator = function (a, b) { | |
var self = this; | |
this.sum = function () { | |
return self.a + self.b; | |
}; | |
} | |
var a = new Operator(1, 2); | |
a.sum(); // 3 | |
a.sum.apply(null, [1, 2]); // 3 | |
a.sum.call(null, 1, 2); // 3 | |
a.sum.apply(a, [1, 2]); // 3 | |
a.sum.call(a, 1, 2); // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment