Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Last active September 12, 2017 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mxriverlynn/28a4072ec51ba71d9556 to your computer and use it in GitHub Desktop.
Save mxriverlynn/28a4072ec51ba71d9556 to your computer and use it in GitHub Desktop.
when "this" attacks with ES6 arrow functions
FileSchema.method("getDownloadUrl", (cb) => {
var options = {
Bucket: "watchmecode-net",
Key: this.name // <= "this" right here, points at the wrong thing!!!
};
var s3 = new AWS.S3();
s3.getSignedUrl("getObject", options, cb);
})
var foo = {};
// a method to create methods
foo.method = function(name, cb){
this[name] = cb;
};
foo.method("bar", function(){
console.log("test");
}
foo.bar(); // => "test"
// run this in node v4 to see the "expected" behavior
this.test = "attached to the module";
var foo = {
test: "attached to an object"
};
// a method to create methods
foo.method = function(name, cb){
this[name] = cb;
};
// use an arrow function and get
// lexical analysis of "this"
foo.method("bar", () => {
// not what you expected, maybe?
console.log(this.test);
});
foo.bar();
// run this in node v4 to see the expected behavior
this.test = "attached to the module";
var foo = {
test: "attached to an object"
};
// a method to create methods
foo.method = function(name, cb){
this[name] = cb;
};
// use standard callback function and get
// the expected "this"
foo.method("bar", function(){
// this one will be what you expected
console.log(this.test);
});
foo.bar(); // => "attached to an object"
// run this in node v4 to see the "expected" behavior
this.test = "attached to the module";
var foo = {
test: "attached to an object"
};
foo.method = function(name, cb){
// bind the value of "this" on the method
// to try and force it to be what you want
this[name] = cb.bind(this);
};
foo.method("bar", () => {
console.log(this.test);
});
foo.bar();
@adityamehra
Copy link

There is the following error in 3.js - Uncaught SyntaxError: missing ) after argument list

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment