JavaScript - Why can't I call a variable “name”?

后端 未结 2 1986
余生分开走
余生分开走 2020-12-07 03:55

Why can\'t you call a variable in JS \"name\"?

var wrapper = document.createElement(\"div\");
var name = document.createElement(\"div\");

wrapper.appendChil         


        
相关标签:
2条回答
  • 2020-12-07 04:03

    Because window.name is a magic property of window object and can hold only strings (any object, including arrays, is coerced to primitive type and becomes something like "[Object Object]"). Variables defined in global scope become properties of global object and it can cause conflicts.

    You can have variable name in any nonglobal scope. Simple workaround can be to wrap your code in immediately-invoked function expression (IIFE).

    (function(){
    
        var wrapper = document.createElement("div");
    
        var name = document.createElement("div");
    
    
        wrapper.appendChild(name); // workd
    
    
        document.body.appendChild(wrapper);
    
    }());
    
    0 讨论(0)
  • 2020-12-07 04:27

    'name' is a predefined name of implementation-dependent JavaScript objects, methods, or properties, you should avoid to use this as a name for a variable, though it's not a reserved word and might work in some browsers

    0 讨论(0)
提交回复
热议问题