首页 新闻 会员 周边

大家来做做这个小小的JS面试题,顺便告诉我为什么是这个答案。。。。

0
悬赏园豆:10 [已关闭问题] 关闭于 2016-10-10 16:24

function Foo(){
abc=function(){alert(1);};
return this;
}
Foo.abc=function(){alert(2);};
Foo.prototype.abc=function(){alert(3);};
var abc=function(){alert(4);};
function abc(){alert(5);};
Foo.abc();//2
abc();//4
Foo().abc();//1
abc();//1
new Foo.abc();//2
new Foo().abc();//3

骑猪敲代码的主页 骑猪敲代码 | 初学一级 | 园豆:200
提问于:2016-10-08 16:02
< >
分享
所有回答(2)
0
function Foo() {
  abc = function() {
    alert(1);
  };
  return this;
}
Foo.abc = function() {
  alert(2);
};
Foo.prototype.abc = function() {
  alert(3);
};
var abc = function() {
  alert(4);
};

function abc() {
  alert(5);
};
Foo.abc(); //2,执行静态方法
abc(); //4, 执行最后的abc函数

Foo().abc(); //1,先执行函数,返回this(由于是函数调用,this = window),
//然后执行this.abc(),也就是window.abc(),由于在Foo函数中,对abc进行了覆盖,所以输出1。

abc(); //同上,abc已被覆盖
new Foo.abc(); //2 执行静态方法abc,然后才是new。
new Foo().abc(); //3 // new Foo(),先实例化,再调用,则是原型方法

 

幻天芒 | 园豆:37175 (高人七级) | 2016-10-08 17:33
0
// 所有变量声明或函数声明都会提升到当前函数的顶部

function Foo(){
    abc = function (){ console.log(1); };
    return this;
}
Foo.abc = function (){ console.log(2); };//函数的方法abc
Foo.prototype.abc = function (){ console.log(3); };//原型方法abc
var abc = function (){ console.log(4); };//函数表达式
function abc(){ console.log(5); };//函数声明
// 以下代码依次执行,输出结果是什么?
Foo.abc();//2  直接访问函数的方法abc
abc();//4
Foo().abc();//1
abc();//1
new Foo.abc();//2
new Foo().abc();//3

// 执行过程
/*function Foo(){//函数声明
    abc = function (){ console.log(1); };
    return this;
}
var abc;
function abc(){ console.log(5); };//覆盖var声明的abc
Foo.abc = function (){ console.log(2); };//函数的方法abc
Foo.prototype.abc = function (){ console.log(3); };//原型方法abc
abc = function (){ console.log(4); };//再次覆盖全局变量abc的值

// 以下代码依次执行,输出结果是什么?
Foo.abc();//2  直接访问函数的方法abc
abc();//4  直接访问全局方法abc
Foo().abc();//1  此时this执行window,Foo执行后abc被重新赋值1
abc();//1  上一句已把abc重新赋值
new Foo.abc();//2  把Foo.abc当成构造函数执行
new Foo().abc();//3  new Foo()实例对象,访问实例对象原型上的方法abc*/

 

骑猪敲代码 | 园豆:200 (初学一级) | 2016-10-10 16:23
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册