Skip to content

Instantly share code, notes, and snippets.

@emartinez-usgs
Created October 1, 2014 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emartinez-usgs/d0f89ec562a29b086d95 to your computer and use it in GitHub Desktop.
Save emartinez-usgs/d0f89ec562a29b086d95 to your computer and use it in GitHub Desktop.
Simplified example showing the potential dangers of using "this" in Javascript.
<!-- Placeholder for Gist Name Only -->
var MyClass = function (message) {
this.message = message;
};
MyClass.prototype.say = function () {
console.log(this.message);
};
var myInstance = new MyClass('hello');
myInstance.say();
var MyClass = function (message) {
this.message = message;
};
MyClass.prototype.say = function () {
console.log(this.message);
};
var message = 'Hacked!';
var myInstance = new MyClass('hello');
myInstance.say.call();
var MyClass = function (message) {
this.message = message;
};
MyClass.prototype.getMessage = function () {
return this.message;
};
MyClass.prototype.say = function () {
console.log(this.getMessage());
};
var message = 'Hacked!';
var getMessage = function () {
return 'Hacked Super Hardcore!';
};
var myInstance = new MyClass('hello');
myInstance.say.call();
var MyClass = function (message) {
this.message = message;
};
MyClass.prototype.getMessage = function () {
return this.message;
};
MyClass.prototype.say = function () {
console.log(this.getMessage());
};
var xss = {
getMessage: function () {
this.maliciousActOne();
this.maliciousActTwo();
this.maliciousActThree();
return 'Mwahahaha!';
},
maliciousActOne: function () { console.log('I am'); },
maliciousActTwo: function () { console.log('so very'); },
maliciousActThree: function () { console.log('malicious.'); }
};
var myInstance = new MyClass('hello');
myInstance.say.call(xss);
var MyClass = function (message) {
var _this = {},
// Instance variable declarations
_message = message,
// Instance method declarations
getMessage,
say;
// Method definitions
getMessage = function () { return _message; };
say = function () { console.log(getMessage()); };
// Expose the public API
_this.getMessage = getMessage;
_this.say = say;
return _this;
};
var xss = {
getMessage: function () {
this.maliciousActOne();
this.maliciousActTwo();
this.maliciousActThree();
return 'Mwahahaha!';
},
maliciousActOne: function () { console.log('I am'); },
maliciousActTwo: function () { console.log('so very'); },
maliciousActThree: function () { console.log('malicious.'); }
};
var myInstance = MyClass('hello');
myInstance.say.call(xss);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment