我正在寫一些使用
Object.bind
的JavaScript
方法。
funcabc = function(x, y, z){
this.myx = x;
this.playUB = function(w) {
if ( this.myx === null ) {
// do blah blah
return;
}
// do other stuff
};
this.play = this.playUB.bind(this);
};
由於我是使用Firefox在winXP中进行開發的,有時是在IE 9或10的win7中进行測試的,所以我没有註意到或註意IE8及以下版本不支援
bind
此特定指令碼不使用画佈,因此我有點犹豫要註销所有IE 8使用者.
有標準的解決方法吗?
我在JavaScript方面還可以,但是還是有點菜鸟.所以,如果解決办法很明顯,請原谅我.
- 5月前1 #
- 5月前2 #
最好的解決方案是安裝Modernizr.
Modernizr告诉您当前瀏覽器是否具有本機實現的此功能 並且它提供了指令碼載入器,因此您可以拉入polyfill来在旧版瀏覽器中迴填功能.
以下是生成您的modernizr自定義版本的鏈接:
Internet Explorer 8及更低版本不支援http://modernizr.com/download/#-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes - 5月前3 #
Function.prototype.bind.此處的相容性圖表:http://kangax.github.io/es5-compat-table/
Mozilla開發人員網路為未原生實現.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; }; }
- 5月前4 #
Function構造函式是執行此操作的老式方法:
var foo = function(x,y,z){ return Function("x,y,z","return Math.max.call(this, x, y, z)")(x,y,z) } var bar = function(x,y,z){ return Function("x,y,z","return Math.min.call(this, x, y, z)")(x,y,z) } console.log(foo(1,2,3) ); console.log(bar(3,2,1) );
References
Functional JavaScript: Harnessing the power of the Function Object
eval() isn’t evil, just misunderstood
[Scope] of Functions Created via the Function constructor
John Resig - Fast JavaScript Max/Min
此頁面上有一个不錯的相容性指令碼: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
只需將其複製並粘贴到指令碼中即可。
EDIT: 為了清楚起见,將指令碼放在下面。