简体   繁体   English

这个对象会一直调用该函数吗?

[英]Will this object always re-call the function?

Here is the first way: 这是第一种方法:

var Objek = {
    node : document.getElementById(known_id),
}

So, when i call Objek.node does this always call the document.getElementById ? 因此,当我调用Objek.node是否总是调用document.getElementById

Is this second way better? 第二种方法更好吗? :

var Objek = (function() {
    var getNode = document.getElementById(known_id);


    return {
        node : getNode
    }
})();

I think this second way is better and wouldn't re-call the document.getElementById when I call Objek.node 我认为这第二种方式是更好的,不会再调用document.getElementById当我打电话Objek.node

In both cases getElementById() is called only once (when you create the object, not when you use objek.node). 在这两种情况下,getElementById()仅被调用一次(创建对象时,而不是使用objek.node时)。

In first case ONLY getElementById() is called and value assigned into new object... 在第一种情况下,仅调用getElementById()并将值分配给新对象...

...while in second case first your function is called, then getNode variable is created, then getElementById() is called and result is assigned to variable and at last new object is created with given property. ...在第二种情况下,首先调用您的函数,然后创建getNode变量,然后调用getElementById()并将结果分配给变量,最后使用给定的属性创建新对象。

So actually first case is both faster to execute and better to understand by developers. 因此,实际上第一种情况执行起来更快,开发人员也更容易理解。

They are equivalent. 它们是等效的。 In both the getElementByIdmethod is called only one time (when you create the object) and then the stored value in the variable is returned at all times when you do Objek.node 在这两种方法中,仅一次调用getElementByIdmethod方法(创建对象时),然后在执行Objek.node时始终返回变量中的存储值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM