console.log(this);
var foo = {
prop: 'hello',
method: function () {
console.log(this);
setTimeout(function () {
console.log(this);
});
}
};
foo.method();
var foo = {
prop: 'hello',
method: function () {
var _this = this;
setTimeout(function () {
console.log(_this.prop);
});
}
};
foo.method();
function bind(fn, ctx) {
return fn.bind(ctx);
}
var Robot = function (robotName) {
this.robotName = robotName;
};
Robot.prototype.sayHello = function () {
console.log('Hello Human, my name is', this.robotName);
};
Robot.prototype.sayHelloDelayed = function (numSeconds) {
setTimeout(bind(this.sayHello, this), numSeconds * 1000);
};
var robby = new Robot('Robby');
robby.sayHello();
robby.sayHelloDelayed(1);
function bind() {
var args = Array.prototype.slice.call(arguments);
;
var fn = args[0];
;
if (arguments.length < 1) {
return this;
}
var self = this;
var args = Array.prototype.slice.call(arguments);
return function() {
return fn.apply(args[1], args.splice(2, args.length));
}
;
}
var Robot = function (robotName) {
this.robotName = robotName;
};
Robot.prototype.sayHello = function (humanName) {
console.log('Hello', humanName + ',', 'my name is', this.robotName);
};
Robot.prototype.sayHelloDelayed = function (humanName, numSeconds) {
setTimeout(bind(this.sayHello, this, humanName), numSeconds * 1000);
};
var robby = new Robot('Robby');
robby.sayHello('Hector');
robby.sayHelloDelayed('Hector', 1);