Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 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 Answer

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

}());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...