Created
February 20, 2014 11:10
-
-
Save sz-alpar/d50f6319fe9b3b6e55db to your computer and use it in GitHub Desktop.
'this' in a method invocation and testing when a function is added to the object.
This file contains hidden or 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
// You need log4javascript for the logging to work | |
// Or use the console, if log4javascript is not available | |
if (typeof log !== 'Object') { | |
log = { | |
debug: function (message) { | |
console.log(message); | |
} | |
} | |
} | |
var object1 = { | |
$get: function () { | |
log.debug(this); | |
this.f = function () { | |
return 42; | |
} | |
} | |
} | |
// When calling $get() directly 'this' points to object1 itself where function f() is not yet added | |
object1.$get(); | |
// But calling f() is possible, because $get() added it | |
object1.f() | |
// Creating a new instance with prototype inheritance | |
function constr() {}; | |
constr.prototype = object1; | |
var instance = new constr(); | |
// Now 'this' inside $get() will point to the new instance where function f() is already added | |
// instance.$get(); | |
log.debug(instance.f()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment