Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

syntax - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

}());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...