89

我只是在阅读这个问题并想尝试使用别名方法而不是函数包装方法,但我似乎无法让它在 Firefox 3 或 3.5beta4 或 Google Chrome 中工作,无论是在他们的调试窗口和在测试网页中。

萤火虫:

>>> window.myAlias = document.getElementById
function()
>>> myAlias('item1')
>>> window.myAlias('item1')
>>> document.getElementById('item1')
<div id="item1">

如果我把它放在一个网页中,对 myAlias 的调用会给我这个错误:

uncaught exception: [Exception... "Illegal operation on WrappedNative prototype object" nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)" location: "JS frame :: file:///[...snip...]/test.html :: <TOP_LEVEL> :: line 7" data: no]

Chrome(为了清楚起见插入了>>>):

>>> window.myAlias = document.getElementById
function getElementById() { [native code] }
>>> window.myAlias('item1')
TypeError: Illegal invocation
>>> document.getElementById('item1')
<div id=?"item1">?

在测试页面中,我得到相同的“非法调用”。

难道我做错了什么?其他人可以重现这个吗?

另外,奇怪的是,我刚刚尝试过,它在 IE8 中工作。

4

6 回答 6

191

我深入研究以了解这种特殊行为,并且我认为我找到了一个很好的解释。

在我解释为什么你不能使用 alias 之前document.getElementById,我将尝试解释 JavaScript 函数/对象是如何工作的。

每当您调用 JavaScript 函数时,JavaScript 解释器都会确定一个范围并将其传递给该函数。

考虑以下功能:

function sum(a, b)
{
    return a + b;
}

sum(10, 20); // returns 30;

此函数在 Window 范围内声明,当您调用它时,thissum 函数内部的值将是全局Window对象。

对于 'sum' 函数,'this' 的值是什么并不重要,因为它没有使用它。


考虑以下功能:

function Person(birthDate)
{
    this.birthDate = birthDate;    
    this.getAge = function() { return new Date().getFullYear() - this.birthDate.getFullYear(); };
}

var dave = new Person(new Date(1909, 1, 1)); 
dave.getAge(); //returns 100.

当您调用 dave.getAge 函数时,JavaScript 解释器会看到您正在对dave对象调用 getAge 函数,因此它会设置thisdave调用该getAge函数。getAge()将正确返回100


您可能知道在 JavaScript 中您可以使用apply方法指定范围。让我们试试看。

var dave = new Person(new Date(1909, 1, 1)); //Age 100 in 2009
var bob = new Person(new Date(1809, 1, 1)); //Age 200 in 2009

dave.getAge.apply(bob); //returns 200.

在上面的行中,不是让 JavaScript 决定范围,而是手动将范围作为bob对象传递。即使您“认为”您调用了该对象,getAge现在也会返回。200getAgedave


以上所有内容有什么意义?函数“松散地”附加到您的 JavaScript 对象上。例如你可以做

var dave = new Person(new Date(1909, 1, 1));
var bob = new Person(new Date(1809, 1, 1));

bob.getAge = function() { return -1; };

bob.getAge(); //returns -1
dave.getAge(); //returns 100

让我们进行下一步。

var dave = new Person(new Date(1909, 1, 1));
var ageMethod = dave.getAge;

dave.getAge(); //returns 100;
ageMethod(); //returns ?????

ageMethod执行抛出错误!发生了什么?

如果您仔细阅读我的上述观点,您会注意到该dave.getAge方法是dave作为this对象调用的,而 JavaScript 无法确定ageMethod执行的“范围”。所以它通过全局'Window'作为'this'。现在由于window没有birthDate属性,ageMethod执行将失败。

如何解决这个问题?简单的,

ageMethod.apply(dave); //returns 100.

以上所有内容都有意义吗?如果是这样,那么您将能够解释为什么您无法使用别名document.getElementById

var $ = document.getElementById;

$('someElement'); 

$windowas调用,this如果getElementById实现是thisdocument它将失败。

再次解决这个问题,你可以做

$.apply(document, ['someElement']);

那么为什么它可以在 Internet Explorer 中运行呢?

我不知道getElementByIdIE 中的内部实现,但是 jQuery 源代码(inArray方法实现)中的注释说在 IE 中,window == document. 如果是这种情况,那么别名document.getElementById应该在 IE 中工作。

为了进一步说明这一点,我创建了一个详细的示例。看看Person下面的函数。

function Person(birthDate)
{
    var self = this;

    this.birthDate = birthDate;

    this.getAge = function()
    {
        //Let's make sure that getAge method was invoked 
        //with an object which was constructed from our Person function.
        if(this.constructor == Person)
            return new Date().getFullYear() - this.birthDate.getFullYear();
        else
            return -1;
    };

    //Smarter version of getAge function, it will always refer to the object
    //it was created with.
    this.getAgeSmarter = function()
    {
        return self.getAge();
    };

    //Smartest version of getAge function.
    //It will try to use the most appropriate scope.
    this.getAgeSmartest = function()
    {
        var scope = this.constructor == Person ? this : self;
        return scope.getAge();
    };

}

对于上述Person函数,以下是各种getAge方法的行为方式。

Person让我们使用函数创建两个对象。

var yogi = new Person(new Date(1909, 1,1)); //Age is 100
var anotherYogi = new Person(new Date(1809, 1, 1)); //Age is 200

console.log(yogi.getAge()); //Output: 100.

直截了当,getAge 方法获取yogi对象作为this并输出100


var ageAlias = yogi.getAge;
console.log(ageAlias()); //Output: -1

JavaScript解释器将window对象设置为this,我们的getAge方法将返回-1


console.log(ageAlias.apply(yogi)); //Output: 100

如果我们设置正确的范围,你可以使用ageAlias方法。


console.log(ageAlias.apply(anotherYogi)); //Output: 200

如果我们传入一些其他人对象,它仍然会正确计算年龄。

var ageSmarterAlias = yogi.getAgeSmarter;    
console.log(ageSmarterAlias()); //Output: 100

ageSmarter函数捕获了原始this对象,因此现在您不必担心提供正确的范围。


console.log(ageSmarterAlias.apply(anotherYogi)); //Output: 100 !!!

问题ageSmarter是您永远无法将范围设置为其他对象。


var ageSmartestAlias = yogi.getAgeSmartest;
console.log(ageSmartestAlias()); //Output: 100
console.log(ageSmartestAlias.apply(document)); //Output: 100

ageSmartest如果提供了无效范围,该函数将使用原始范围。


console.log(ageSmartestAlias.apply(anotherYogi)); //Output: 200

您仍然可以将另一个Person对象传递给getAgeSmartest. :)

于 2009-07-21T23:00:27.317 回答
42

您必须将该方法绑定到文档对象。看:

>>> $ = document.getElementById
getElementById()
>>> $('bn_home')
[Exception... "Cannot modify properties of a WrappedNative" ... anonymous :: line 72 data: no]
>>> $.call(document, 'bn_home')
<body id="bn_home" onload="init();">

当你做一个简单的别名时,这个函数是在全局对象上调用的,而不是在文档对象上。使用一种称为闭包的技术来解决这个问题:

function makeAlias(object, name) {
    var fn = object ? object[name] : null;
    if (typeof fn == 'undefined') return function () {}
    return function () {
        return fn.apply(object, arguments)
    }
}
$ = makeAlias(document, 'getElementById');

>>> $('bn_home')
<body id="bn_home" onload="init();">

这样您就不会失去对原始对象的引用。

2012 年,bind来自 ES5 的新方法允许我们以更奇特的方式做到这一点:

>>> $ = document.getElementById.bind(document)
>>> $('bn_home')
<body id="bn_home" onload="init();">
于 2009-06-17T14:35:29.387 回答
3

这是一个简短的答案。

以下是该函数的副本(引用)。问题是,当函数window被设计为存在于对象上时,它现在位于对象上document

window.myAlias = document.getElementById

替代方案是

  • 使用包装器(Fabien Ménager 已经提到过)
  • 或者您可以使用两个别名。

    window.d = document // A renamed reference to the object
    window.d.myAlias = window.d.getElementById
    
于 2011-02-03T17:55:28.180 回答
2

另一个简短的答案,仅用于包装/别名console.log和类似的日志记录方法。他们都希望在console上下文中。

这在使用一些后备包装时很有用,以防您或您的用户在使用不(总是)支持它的浏览器console.log时遇到麻烦。但是,这并不是该问题的完整解决方案,因为它需要扩展检查和后备 - 您的里程可能会有所不同。

使用警告的示例

var warn = function(){ console.warn.apply(console, arguments); }

然后照常使用

warn("I need to debug a number and an object", 9999, { "user" : "Joel" });

如果您希望看到包含在数组中的日志记录参数(我经常这样做),请替换.apply(...).call(...).

应该与console.log(), console.debug(), console.info(), console.warn(),一起使用console.error()。另请参阅consoleMDN

于 2012-02-03T10:06:34.433 回答
1

除了其他很好的答案之外,还有简单的 jQuery 方法$.proxy

你可以这样别名:

myAlias = $.proxy(document, 'getElementById');

或者

myAlias = $.proxy(document.getElementById, document);
于 2012-08-17T04:23:40.403 回答
-6

您实际上不能在预定义对象上“纯别名”函数。因此,在不进行包装的情况下,最接近别名的方法是保持在同一个对象内:

>>> document.s = document.getElementById;
>>> document.s('myid');
<div id="myid">
于 2009-06-29T17:44:28.290 回答