Created
April 30, 2014 14:58
-
-
Save nealfennimore/11429442 to your computer and use it in GitHub Desktop.
Always a This Javascript
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
// this | |
console.log(this); // window | |
function firstFunction() { | |
console.log("Hello world"); // Hello world | |
console.log(this); //window | |
} | |
function Person(name) { | |
this.name = "Jane Doe"; | |
// this.name = name || "Jane Doe"; sets default | |
// this.name = name || this.DEFAULT_NAME; also sets default with prototype | |
console.log(this); | |
} | |
// Person.prototype.DEFAULT_NAME = "Jane Doe"; | |
// Person.prototype = { | |
// DEFAULT_NAME: "Jane Doe", | |
// save: function(){ | |
// } | |
// }; | |
// Multi-line object. Not recommened as will override other prototypes | |
// new Person(); { name: "Jane Doe" } | |
// new is constructor function, creates new object | |
// Person(); { name: "Jane Doe" } | |
Person.prototype.save = function() { | |
var self = this; // Gives access to Person object | |
$.post("/people", {name: this.name}, function(resp){ | |
// this == jQxhr | |
self.id = resp.id; // this == Person | |
}, "json"); | |
}; | |
// -------------- Technique two | |
Person.prototype.save = function() { | |
$.post("/people", {name: this.name}, function(resp){ | |
this.id = resp.id; | |
}.bind(this), "json"); // value of this is passed to bind (i.e. Person) | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment