Как обрабатывать недостаток JavaScript Object.bind() в IE 8
Я пишу немного JavaScript, который использует метод Object.bind
.
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);
};
Поскольку я разрабатываю WinXP с Firefox и иногда тестирую в Win7 с IE 9 или 10, я не заметил и не обратил внимание на то, что IE8 и ниже не поддерживают bind
.
Этот конкретный script не использует холст, поэтому я немного не решаюсь списать всех пользователей IE 8.
Есть ли стандартный режим работы?
В JavaScript я обойдусь, но я все еще немного нуб. Так что простите меня, если решение полностью очевидно.
Ответы
Ответ 1
На этой странице есть хорошая совместимость script:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
Просто скопируйте и вставьте его в свой script.
РЕДАКТИРОВАТЬ: размещение script ниже для ясности.
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;
};
}
Ответ 2
Лучшим решением может быть установка Modernizr.
Modernizr сообщает вам, имеет ли текущий браузер эту функцию, реализованную или нет
и он обеспечивает загрузчик script, чтобы вы могли вытаскивать полиполки для выполнения функций обратной засыпки в старых браузерах.
Вот ссылка для создания вашей версии customizr:
http://modernizr.com/download/#-teststyles-testprop-testallprops-hasevent-prefixes-domprefixes
Ответ 3
Функция .prototype.bind не поддерживается в Internet Explorer 8 и ниже. Диаграмма совместимости здесь: http://kangax.github.io/es5-compat-table/
Mozilla Developer Network предоставляет эту альтернативу для старых браузеров, которые не реализованы .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;
};
}
Ответ 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) );