Heim > Web-Frontend > js-Tutorial > Hauptteil

ie支持function.bind()方法实现代码_javascript技巧

WBOY
Freigeben: 2016-05-16 17:45:12
Original
826 Leute haben es durchsucht

前端开发者应该很清楚 Javscript 脚本的 function 函数对象可以通过 call 或 apply 方法,使其改变内部作用域(this)所指向的对象,实现更多可扩展的功能开发。ie 原生支持 function 对象的 call 和 apply 方法,在 firefox 或其它浏览器下也得到支持,但是 call 和 apply 方法是立即作用并执行,例如:

复制代码 代码如下:

var func = function () {
alert(this);
}.apply(window);

当脚本解析引擎执行到这段代码时,会立即弹出对话框并显示 object 字符串。我们的初衷是想定义 func 方法作用在 window 对象域上,并在后期调用时再执行,但是 call 和 apply 方法并不能满足我们的初衷,它们会立即得到执行。

在 google 一番技术资料后,发现 firefox 原生支持一个 bind 方法,该方法很好的满足了我们的初衷,调用方法与 call 和 apply 一样,只是定义完成后,在后期调用时该方法才会执行。但是这个 bind 方法只有在 ie10 版本的浏览器才得到原生支持,低于该版本的浏览器下执行时会得到一个 undefined 的错误提示。于是只好再次上网 google 解决方案,功夫不负有心人,我们在 firefox 的开发站找到了解决方案,那就是增加 property 原型使得所有浏览器都能支持 bind 方法,代码如下:
复制代码 代码如下:

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,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}

看懂这段代码需要点功底,我只是知道如何拿来用,如果哪位大牛有兴趣能够介绍一下这段源码的原理,不胜感激,谢谢!

单纯不是什么态度,而是一种满足。
Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!