Javascript 面试题随笔

时间:2024-04-29 13:44:53 


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还是一个很好玩的语言。

标签:面试题
0
投稿

猜你喜欢

  • VSCode开发必备插件推荐(墙裂推荐!)

    2022-06-21 14:09:16
  • Python 中的装饰器实现函数的缓存(场景分析)

    2022-07-30 01:37:08
  • Python猫眼电影最近上映的电影票房信息

    2023-07-02 18:05:01
  • PyTorch中torch.utils.data.DataLoader简单介绍与使用方法

    2023-10-30 07:12:00
  • Python命令行参数argv和argparse该如何使用

    2022-04-05 01:38:52
  • 如何使用Python Matplotlib绘制条形图

    2023-09-21 04:41:46
  • 简单介绍Python中的RSS处理

    2023-03-03 13:59:17
  • python列表倒序的几种方法(切片、reverse()、reversed())

    2022-01-28 02:46:52
  • Request.ServerVariables各参数说明集合

    2008-11-25 18:49:00
  • centos+nginx+uwsgi部署django项目上线

    2023-12-13 03:36:31
  • php实现mysql事务处理的方法

    2023-11-10 10:42:39
  • 解读调用jupyter notebook文件内的函数一种简单方法

    2021-04-19 09:47:56
  • javascript根据像素点取位置示例

    2023-09-03 22:58:54
  • 详解MySQL 慢查询

    2024-01-26 19:00:58
  • MySQL中基本的用户和权限管理方法小结

    2024-01-24 20:03:49
  • 在SQL Server2000中恢复Master数据库

    2008-01-05 14:05:00
  • JavaScript中的一些实用小技巧总结

    2024-04-10 10:45:15
  • MySQL数据库中的各种乱码及其解决方法

    2008-12-17 16:29:00
  • 基于django 的orm中非主键自增的实现方式

    2023-06-04 13:53:54
  • Dreamweaver量身打造Wordpress留言板(三)

    2009-12-13 18:45:00
  • asp之家 网络编程 m.aspxhome.com