пятница, 15 июня 2012 г.

jQuery: "name.replace is not a function" error

It's a very widely known error, since jQuery 1.0 probably. I'll describe he solution en English, because there aren't any English manual for it too.

If you implement the OOP inheritance in JavaScript using this very famous code:

Object.prototype.Inherits = function(parent)
{
 if(arguments.length > 1)
  parent.apply(this, Array.prototype.slice.call(arguments,1));
 else
  parent.call(this);
}

Function.prototype.Inherits = function(parent)
{
 this.prototype = new parent();
 this.prototype.constructor = this;
}

fadeIn() and fadeOut() will cause this error :-(.

Anyway, this version of inheritance isn't so good at all, because it breaks JavaScript foreach-like for too, adding 1 more element "Inherits" to every array.

But what if you have to use it? Is there any way to fix?

Firstly, update this implementation to make it safe:

Object.prototype.Inherits = function(parent)
{
 if(!parent || typeof(parent.call) != "function")
  return;
 if(arguments.length > 1)
  parent.apply(this, Array.prototype.slice.call(arguments,1));
 else
  parent.call(this);
}

Function.prototype.Inherits = function(parent)
{
 this.prototype = new parent();
 this.prototype.constructor = this;
}

Then update jQuery.js (is you have a min version, replace it with full one). Find "getComputedStyle = function( elem, name ) {" and add after first 2 lines:

getComputedStyle = function( elem, name ) {
 var ret, defaultView, computedStyle, width,
  style = elem.style;
 //Add this:
 if(typeof(name) != "string")
  return name;
 //-----

And it will work fine :-)

Комментариев нет:

Отправить комментарий