Door Gaya Kessler / @GayaNinja
Site: http://gaya.ninja
Blog: http://blog.gaya.ninja
Twitter: @GayaNinja
this
?this
?var obj = {
name: "Barry",
bar: function () {
console.log(this.name);
}
}
obj.bar(); //Barry
setTimeout(obj.bar, 10); //Storage
obj //<-- call-site for obj.bar()
.bar();
setTimeout(obj.bar, 10); //not the call-site for obj.bar()
//passes function obj.bar, not the object
function setTimeOutCallback(callback) {
callback(); //<-- call-site for obj.bar()
}
function
?function Foo() {
this.count++;
}
Foo.count = 0;
Foo();
Foo();
Foo();
console.log(Foo.count); //0
function Foo() {
this.count++;
}
Foo(); // <-- call-site for Foo() is `Window`
.bind()
is de oplossingvar that = this;
var obj = {
name: "Barry",
bar: function () {
console.log(this.name);
}
}
obj.bar(); //Barry
setTimeout(obj.bar.bind(obj), 10); //Barry
function Foo() {
this.count++;
}
Foo.count = 0;
Foo.call(Foo);
Foo.call(Foo);
Foo.call(Foo);
console.log(Foo.count); //3
var newUser = User();
newUser.name = getName(); //Ad
newUser.town = getTown(); //Universe
newUser.age = getAge(); //42
[...]
newUser.save();
var newUser = User();
getName(function handleName(name) {
newUser.name = name; });
getTown(function gotTown(town) {
newUser.town = town; });
getAge(function gotAge(age) {
newUser.age = age; });
console.log(newUser.name, newUser.town, newUser.age);
//undefined undefined undefined
var newUser = User();
getName(function handleName(name) {
newUser.name = name;
getTown(function handleTown(town) {
newUser.town = town;
getAge(function handleAge(age) {
newUser.age = age;
newUser.save();
});
});
});
var newUser = User();
getName(handleName);
function handleName(name) {
newUser.name = name; getTown(handleTown); }
function handleTown(town) {
newUser.town = town; getAge(handleAge); }
function handleAge(age) {
newUser.age = age; newUser.save(); }
class
is slechts een blauwdruk.var Foo = {
name: "Barry",
bar: function () {
console.log(this.name); }
}
var Loel = {
name: "Ad",
all: Foo.bar
}
Loel.all(); //Ad
/CoolStuff/
index.js
logic.js
/Other/
index.js
index.js
var CoolStuff = { ... }
module.exports = function () {
var newObject = Object.create(CoolStuff);
newObject.iets = "Iets";
newObject.method();
return newObject;
}
var CoolStuff = require("./CoolStuff/");
CoolStuff(); //instant throw away
var stuff = CoolStuff(); //keep in object
PHP / JSP / .NET / Ruby
HTML, CSS, JavaScript
JavaScript (Node.js, io.js)
HTML, CSS, JavaScript
require
======= >>>>>>> fd2532a2f09a151b6572476352d606c3fecfd947