为什么e.name不返回与e().name相同的值?不是事件对象

Why does e.name not return the same value as e().name? Not the event object

本文关键字:name 对象 事件 返回 为什么      更新时间:2023-09-26

我基本上一直在玩一些JavaScript链接,并正在查看jQuery源代码,试图了解它们是如何做一些事情的。我知道它们在全局$$()上有不同的功能,但我认为有些是相同的?

我也想知道我是否可以得到一些帮助来理解发生了什么。不确定其他用例链接会有什么,但我希望能更好地理解其内部结构。

这是我的代码(它现在可以正常工作,看看答案澄清:

/*
Chaining stuff
*/
var e = function() {
    return new e.ext.init();
};
e.ext = {
    _name: 'test',
    init: function() {
        console.log('init');
        return this;
    },
    chainA: function() {
        console.log('chainA');
        return this;
    },
    chainB: function() {
        console.log('chainB');
        return this;
    }
};
/*
* Fix the value of `this` in `e.ext.init
* by setting its prototype to the value
* of `e.ext`
*/
e.ext.init.prototype = e.ext;
// e and e() can have the same properties if we loop through e.ext and add them
for(var prop in e.ext) {   
    e[prop] = e.ext[prop];
}
// log output
console.log('-- logging chaining demo --'n');
console.log(e._name);
e.chainA().chainB();
console.log(''n');
console.log(e()._name);
e().chainA().chainB();
http://jsfiddle.net/edhedges/EM6Ck/

编辑:这怎么离题了?另外,为什么ee.chainA()一样工作的功能与e().chainA()相同?

在您的示例中,e是一个函数,而不是对象。所以你的窒息点在这里:

for(var prop in e.ext) {   
    e[prop] = e.ext[prop];
}

我在每次赋值后加上console.log(e[prop]);,得到empty string和三个function()的结果;

此外,当我调用e['chainA']()时,我得到chainA响应。所以我猜你实际上可以分配其他类似的函数,做出某种形式的组合。但它不能与其他任何东西一起工作。

实际上Javascript: The Definitive Guide给出了这个例子:

uniqueInteger.counter = 0;
// This function returns a different integer each time it is called.
// It uses a property of itself to remember the next value to be returned.
function uniqueInteger() {
   return uniqueInteger.counter++;    
}

,它工作!

console.log(uniqueInteger()); //0
console.log(uniqueInteger()); //1
console.log(uniqueInteger.counter); //2

即使变量被引用为数组字面量也是有效的。因此,这种奇怪行为背后的真正原因似乎在其他地方。

我是愚蠢的。这是你的答案(来自MDN):

 Function.name
    The name of the function.

所以你只是试图覆盖一个Function对象的内部属性,我猜,不会这样工作。它是一个空字符串,因为e是一个匿名函数,这现在非常有意义。

使用e()创建对象,而简单地使用e只返回创建对象的函数。