幽灵资源网 Design By www.bzswh.com
复制代码 代码如下:
var Fundamental = {count:1};
function Test(){}
Test.prototype = Fundamental;
Test.prototype.increase = function(){this.count++;};
var test = new Test();
console.log(test.count);
var test2 = new Test();
console.log(test2.count);
test.increase();
//test.count和test2.count的值各是多少
前天去面试遇到的一道题,面试的问题大概是当test.increase被调用时,test和test2的count值分别是多少
首先,回答这道题有可能把这种情况与另一种类似的情况相混淆:
假如把代码改成:
复制代码 代码如下:
function FundamentalModified(){
var count = 1;
this.increase = function(){
count++;
}
this.show = function(){
return count;
}
}
function TestModified(){}
TestModified.prototype = new FundamentalModified();
var test3 = new TestModified();
var test4 = new TestModified();
test3.increase();
//test3.show()和test4.show()各是多少
假如问题改成这样,那就简单的多了。但是两个问题并不会得到相同的结果。
==========================================分割一下
回到面试题中,其实面试题的答案是2和1。原因呢:test.count是test的属性,而且test2.count其实是test2.__proto__的属性:
var Fundamental = {count:1};
function Test(){}
Test.prototype = Fundamental;
Test.prototype.increase = function(){this.count++;};
var test = new Test();
console.log(test.count);
var test2 = new Test();
console.log(test2.count);
test.increase();
//test.count和test2.count的值各是多少
前天去面试遇到的一道题,面试的问题大概是当test.increase被调用时,test和test2的count值分别是多少
首先,回答这道题有可能把这种情况与另一种类似的情况相混淆:
假如把代码改成:
复制代码 代码如下:
function FundamentalModified(){
var count = 1;
this.increase = function(){
count++;
}
this.show = function(){
return count;
}
}
function TestModified(){}
TestModified.prototype = new FundamentalModified();
var test3 = new TestModified();
var test4 = new TestModified();
test3.increase();
//test3.show()和test4.show()各是多少
假如问题改成这样,那就简单的多了。但是两个问题并不会得到相同的结果。
==========================================分割一下
回到面试题中,其实面试题的答案是2和1。原因呢:test.count是test的属性,而且test2.count其实是test2.__proto__的属性:
当test.increase()被调用时,JS执行了this.count++ ==> 返回this.count; this.count = this.count + 1;
this.count = this.count + 1;
这句在看似简单的语句其实有着不同寻常的意味~~
这句话的意思其实是,给实例新建一个属性,这个属性被赋予this.count + 1的值。
而this.count 其实是在原型链中的count,也就是这个this.count++其实在第一次执行的时候表现为:
this.count = Test.Prototype.count + 1;
可以用hasOwnProperty来验证一下:
当var test = new Test()时。test.hasOwnProperty("count") === false
test.increase()后。 test.hasOwnProperty("count") === true
总的来说,JS还是一个很好玩的语言。
标签:
面试题
幽灵资源网 Design By www.bzswh.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
幽灵资源网 Design By www.bzswh.com
暂无评论...
P70系列延期,华为新旗舰将在下月发布
3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。
而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?
根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。