简体   繁体   中英

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

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

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

wrapper.appendChild(name); // TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

document.body.appendChild(wrapper);

When I type "name" in the console in a new tab it returns an empty string?

I use Chrome.

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);

}());

'name'是依赖于实现的JavaScript对象,方法或属性的预定义名称,您应该避免将其用作变量的名称,尽管它不是保留字并且可能在某些浏览器中有效

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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