var name = "pig";
function Person(name){
this.name = name;
this.getName = function(){
setTimeout(function(){
console.log("Hello,my name is "+this.name);
},100);
}
}
var weiqi = new Person("卫旗");
weiqi.getName();
//Hello,my name is pig
var name = "pig";
function Person(name){
this.name = name;
this.getName = function(){
//在这里缓存一个this
var self = this;
setTimeout(function(){
//在这里是有缓存this的self
console.log("Hello,my name is "+self.name);
},100);
}
}
var weiqi = new Person("卫旗");
weiqi.getName();
//Hello,my name is 卫旗
var name = "pig";
function Person(name){
this.name = name;
this.getName = function(){
setTimeout(function(){
console.log("Hello,my name is "+this.name);
}.bind(this),100);
//注意上面这一行,添加了bind(this)
}
}
var weiqi = new Person("卫旗");
weiqi.getName();
//Hello,my name is 卫旗
//定义全局变量x
var x = "window";
//在module内部定义x
var module = {
x:"module",
getX:function(){
console.log(this.x);
}
}
module.getX();
//返回module,因为在module内部调用getX()
var getX = module.getX;
getX();
//返回window,因为这个getX()是在全局作用域中调用的
//绑定getX()并将this值设为module
var boundGetX = getX.bind(module);
boundGetX();
//返回module,绑定以后this值始终为module
| Browser | Version support |
|---|---|
| Chrome | 7 |
| FireFox(Gecko) | 4.0(2) |
| Internet Explorer | 9 |
| Opera | 11.60 |
| Safari | 5.14 |
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP && oThis
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
fun.bind(thisArg[, arg1[, arg2[, …]]])
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有