有关JavaScript中的prototype.bind()方法介绍
来源:才华咖 本文已影响3.2W人
来源:才华咖 本文已影响3.2W人
以前,你可能会直接设置self=this或者that=this等等,这样做当然也能起作用,但是使用()会更好,看上去也更专业。
下面举个简单的例子:
复制代码 代码如下:
var myObj = {
specialFunction: function () {
},
anotherSpecialFunction: function () {
},
getAsyncData: function (cb) {
cb();
},
render: function () {
var that = this;
syncData(function () {
ialFunction();
herSpecialFunction();
});
}
};
er();
在这个例子中,为了保持myObj上下文,设置了一个变量that=this,这样是可行的,但是没有使用()看着更整洁:
复制代码 代码如下:
render: function () {
syncData(function () {
ialFunction();
herSpecialFunction();
}(this));
}
在调用()时,它会简单的创建一个新的函数,然后把this传给这个函数。实现()的代码大概是这样的:
复制代码 代码如下: = function (scope) {
var fn = this;
return function () {
return y(scope);
};
}
下面在看一个简单的使用()的.例子:
复制代码 代码如下:
var foo = {
x: 3
};
var bar = function(){
(this.x);
};
bar(); // undefined
var boundFunc = (foo);
boundFunc(); // 3
是不是很好用呢!不过遗憾的是IE8及以下的IE浏览器并不支持()。支持的浏览器有Chrome 7+,Firefox 4.0+,IE 9+,Opera 11.60+,Safari 5.1.4+。虽然IE 8/7/6等浏览器不支持,但是Mozilla开发组为老版本的IE浏览器写了一个功能类似的函数,代码如下:
复制代码 代码如下:
if (!) {
= function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError(" - what is trying to be bound is not callable");
}
var aArgs = (arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return y(this instanceof fNOP && oThis
? this
: oThis,
at((arguments)));
};
otype = otype;
otype = new fNOP();
return fBound;
};
}
Jolie drops battle over perfume named Shilohy英语作文
A Letter to Univsity Pesident about the Canteen Service on C
关于 response方法的javascript asp教程第六课
JavaScript中创建字典对象(dictionary)的实例
初中英语写作范文:My Happy Times During Winter Vacation
whats your plan for dragon boat festival英语作文
The relationship between theory and practice大学英语作文
My Happy Times During Winter Vacation初中英语作文
Happy Dragon Boat Festival英语作文
关于JavaScript中isPrototypeOf函数作用和使用实例
关于javascript中encodeURI和decodeURI的使用方法
ASandpiperToBringYouJoy英语阅读
JavaScript toFixed方法介绍
JavaScript中的原型链prototype详解
Why Public Speaking Is So Important 公共演说的重要性大学英语
关于异步JavaScript编程中的Promise使用方法
,javascript break和continue区别
英语阅读:Are You Tricked by These Optical Illusions
中考英语阅读理解答案A report from the United Nations
JavaScript fontcolor方法入门实例
有关JavaScript中的prototype.bind()方法介绍
Ought Parents to Give Children Pocket英语作文
有关于求职中的自我介绍
jQuery中的read和JavaScript中的onload函数的区别在哪
World Day to Combat Desertification大学英语作文
The Development of a Private Car英语作文
Food and place of interest in Beijing初中英语作文
私家车的坏处The Disadvantages of Private Cars英语作文
八年级《unit8 Why don’t you get her a scarf? Period1》评课稿
Efforts Urged to Improve Womens Reproductive Health英语阅读
javascript中toString()的用法
如何在Javascript中为String对象添加trim,ltrim,rtrim方法
Its Our Duty To Protect Our Environment-作文及点评
有关自我介绍的方法
A Letter to the Editor of a Newspaper英语四级作文
Javascript中设立对象的ReadOnly属性
The Best Thing That Could Ever Happen少儿双语阅读
中学学习方法介绍
Chimp Cops Arbitrate Disputes美文欣赏
四级作文:Create a Conservation-Oriented Campus