object name same a function name?

前端 未结 6 1398
余生分开走
余生分开走 2020-12-17 00:35

If We have

var randomname = {};
randomname.attribute = \'something\';

function randomname(){
  alert(randomname.attribute);
}
randomname();
6条回答
  •  时光说笑
    2020-12-17 00:39

    Your function randomname() is redefining the randomname identifier, thus losing your reference to the object you constructed earlier. It may look more clear like this:

    var randomname = {};
    randomname.attribute = 'something';
    
    var randomname = function () {
      alert(randomname.attribute);
    };
    
    randomname();
    

    It is like doing:

    var a = 5;
    var a = [20, 30];
    
    console.log(a);  // returns [20, 30]
    

提交回复
热议问题