JS基础 - instanceof 理解及手写

基于粒子群算法的PID控制器优化设计 粒子群算法、PID、寻优 阅读详情
AI摘要

本文围绕 JS 中的 instanceof 运算符展开。介绍了其作用是检测构造函数的 prototype 属性是否在实例对象原型链上,还给出了手写实现思路。深入探究了其特点,如左侧为原始值返回 false 等。此外,提到了 Symbol.hasInstance 可自定义 instanceof 在自定义类上的行为。

在 JS 中,一般情况下,我们想判断某个引用值的类型,可以使用 instanceof 运算符,如 [] instanceof Array,其返回值为布尔值。

但如果运行 [] instanceof Object,会发现其结果也是 true,这时我们可能会想当然地认为“数组也是广义上的对象,所以结果是 true”,这个结论本身是没有问题的,但我们还是需要站在 instanceof 的角度上看看,它使用什么标准去评判返回值是 true 还是 false。

一、基础理解

MDN 上对 instanceof 作用的描述为:

检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

翻译成人话就是:左侧操作数是一个对象,右侧操作数是一个构造函数,如果右侧构造函数的原型对象存在于左侧对象的原型链上,返回值为 true,反之为 false。

既然我们知道了两个最重要的信息,就是 原型链和 原型对象,那么我们就可以转换成代码的角度去思考,如何实现自己的 instanceof 函数了:

  1. 获取构造函数的原型对象(即其 prototype 属性)
  2. 循环读取对象的 __proto__ 属性来遍历其原型链
  3. 如果构造函数的原型对象,与原型链上的某个对象相等(堆内存地址相等),则跳出循环,返回 true
  4. 如果循环读取 __proto__ 至原型链末端 null(即 Object.prototype.__proto__),则证明原型链上不存在构造函数的原型对象,返回 false。 根据上述思路,我们可以编写自己的 myInstanceof 函数:
function myInstanceof(target, constructor) {
  // 构造函数的原型对象
  const prototype = constructor.prototype
  // 用于存放target的原型链
  let proto = target.__proto__

  // 一直循环寻找,直至原型链末端
  while (proto !== null) {
    if (proto === prototype) return true
    proto = proto.__proto__
  }
  return false
}

补充说明:
文章会使用 __proto__ 属性来读取实例对象的构造函数的原型对象,但实际上这是非标准的用法(即使它被广泛支持)。
标准做法应是调用 Reflect.getPrototypeOf()函数。
但为了使文章代码更通俗简易,现直接使用 __proto__ 属性。

作者:LRH
链接:https://juejin.cn/post/7513764825266569268
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

二、进阶理解

除了上述主体逻辑之外,我们还可以深入探究 instanceof 运算符的特点:

  1. 左侧操作数可以是原始值,不会报错,但会直接返回 false
  2. 右侧操作数 a. 必须是广义上的对象 b. 必须是能读取到 Symbol.hasInstance 属性(当然它是一个函数),然后调用它,并将左侧操作数作为实参传入

这里再提供一些关于 Symbol.hasInstance 的独家消息:

  1. 实际上 Symbol.hasInstance 是存放于 Function.prototype 中的,所以只需判断右侧操作数是否是函数,就能判断它是否是能读取到 Symbol.hasInstance 属性的对象了。
  2. 而众所周知,箭头函数也是函数,它同样能通过原型链访问 Symbol.hasInstance,但它的特殊点在于箭头函数是没有 prototype 属性的,所以将箭头函数作为右侧操作数同样会报错。

根据以上信息,完善 myInstanceof:

function myInstanceof(target, constructor) {
  // 根据instanceof的特性:第一个参数如果是原始值,则返回false
  if (target === null || (typeof target !== 'object' && typeof target !== 'function')) {
    return false
  }
  // 第二个参数必须为函数,否则会抛出错误
  if (typeof constructor !== 'function') {
    throw new TypeError('argument[1] is not callable')
  }

  // 构造函数的原型对象
  const prototype = constructor.prototype
  // 当constructor为箭头函数时,prototype为undefined,抛出错误
  if (prototype === undefined) {
    throw new TypeError("arguments[1] has non-object prototype 'undefined' in instanceof check")
  } 
  
  // 用于存放target的原型链
  let proto = target.__proto__

  // 一直循环寻找,直至原型链末端
  while (proto !== null) {
    if (proto === prototype) return true
    proto = proto.__proto__
  }
  return false
}

// =======测试用例==========

// 左侧操作数为原始值
console.log(myInstanceof(123, Number)) // false
console.log(myInstanceof(null, Object)) // false
console.log(myInstanceof(undefined, Object)) // false

// 常规情况,左侧为对象,右侧为构造函数
console.log(myInstanceof([], Array)) // true
console.log(myInstanceof([], Object)) // true
console.log(myInstanceof([], String)) // false

// 右侧操作数为非函数
try {
  console.log(myInstanceof({}, {}))
} catch (e) {
  console.log(e.message) // argument[1] is not callable
}

// 右侧操作数为箭头函数
try {
  console.log(myInstanceof({}, (() => {})))
} catch (e) {
  console.log(e.message) // arguments[1] has non-object prototype 'undefined' in instanceof check
}

三、关于 Symbol.hasInstance

JS 引擎规定了 Function.prototype[Symbol.hasInstance] 是不可被重新赋值的,但通过 Symbol.hasInstance,我们可以在定义类的时候,规定 instanceof 在自定义类上的行为。

以下是 MDN 中在自定义类中重写 Symbol.hasInstance 的例子。需要注意的是,在自定义类中,需要将 Symbol.hasInstance 作为静态方法,而不是定义在其 prototype 上。

class MyArray {
  // 静态方法
  static [Symbol.hasInstance](instance) {
    // instance就是左侧操作数
    return Array.isArray(instance);
  }
}
console.log([] instanceof MyArray); // true

四、总结

可以认为 instanceof 运算符的工作原理,实际上是调用右侧操作数的 Symbol.hasInstance 函数,并将左侧操作数作为参数传入,返回函数的返回值。

而默认的 Symbol.hasInstance 函数是存放在 Function.prototype 中的。其主要逻辑是检测右侧构造函数的原型对象,是否存在于左侧对象的原型链上,如果存在返回 true,反之返回 false。

由于 JS 引擎的限制,我们无法对 Function.prototype[Symbol.hasInstance] 进行重新赋值,但是在自定义类中,我们可以通过 Symbol.hasInstance 来自定义 instanceof 的行为。

金融波动率的“捕手”:GARCH模型,揭秘市场波动的“聚集密码” 摘要: GARCH模型(广义自回归条件异方差)是金融时间序列分析中用于捕捉“波动聚类”现象的核心工具。传统模型(如ARIMA)无法刻画金融数据的时变波动特性,而GARCH通过建模条件方差的动态变化(如$\sigma_t^2 = \omega + \alpha \varepsilon_{t-1}^2 + \beta \sigma_{t-1}^2$),精准预测波动率。Python实战显示,GARCH能有效拟合模拟金融数据的波动聚类,残差无自相关,验证了其优越性。该模型在波动率预测、风险价值(VaR)计算和期权定 阅读详情

相关推荐

niushop靶场漏洞查找-文件上传漏洞等(超详细)

发现报错,而且这个报错十分熟悉,与我们所学的sqli报错注入特别像。这里查询到后面的url有且仅有一个,目测估计是后台。上传的图片是包含一句话木马的图片。发现获取到了webshell。实战漏洞-niushop。

qq_59020256的博客 1732

JS之instanceof详解

instanceof 用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。 语法:object instanceof constructor object:某个实例对象 constructor:某个构造函数 用来检测 constructor.prototype 是否存在于参数 object 的原型链上。 示例 // 定义构造函数 function C () {} function D () {} // 实例化一个 o 对象 var o = new C() // tru

wfly blog 12万+

【IT小趣闻】免费的DeepSeek是如何赚钱的?

导语:目前很多的通用人工智能也就是所谓的AGI例如文心一言、豆包、通义千问和最近大火的DeepSeek都是免费给普通用户使用的,对开源商业模式不太熟悉的普通人可不太了解这免费背后的商业套路,下面我们就一起来揭秘。开源模式能降低用户信任成本、加速技术普及,而商业化服务则针对企业级需求。DeepSeek 可通过组合上述策略,在服务开发者社区的同时,满足企业客户的深度需求,实现可持续发展。你也看出来了,上边是DeepSeek生成的,讲的还是挺明白的。

SunMy的博客 1795

js中的instanceof原理

instanceof是用来检测构造函数的属性是否出现在某个实例对象的原型链上。但是也存在缺陷,就是它不能精确的判断 Object 类的具体数据类型。如何实现instanceof?

分享学习成果,希望可以帮助到你。 3690

SAP Business One自定义表与字段实战:从零构建企业专属数据模型

本文详细介绍了如何在SAP Business One中创建自定义表与字段,从零构建企业专属数据模型。通过实战案例和避坑指南,帮助用户掌握业务适配、流程优化和权限隔离等关键技巧,提升系统灵活性和数据管理效率。特别适合需要扩展标准功能的SAP Business One用户。

weixin_28730927的博客 370

MCAL知识点(十):ERU驱动配置详解

ERS:外部请求单元ETL:中断逻辑单元OGU:输出逻辑单元MCU里面配置要使用的功能和选择输入的管脚,注意上述模块关注点讲述的ERU必须和边沿检测模块相关联。

梦想技术家 1228

js的各种数据类型判断(typeof、instanceof、Object.prototype.toString.call()、constructor、in、hasOwnProperty)

1.typeof Object.prototype.toString.call() constructor in hasOwnProperty() 基础类型: String、Number、Boolean、null、undefined、Symbol 存储在栈中,赋值变量和比较均为数据本身。 引用类型:Object、Array、Map、Function 存储在堆中,使用new创建,赋值变量和比较均是内存地址。

muzidigbig的博客 1万+

【NVIDIA-GB200-1】国内第一份生产环境实战安装配置教程,配置安装脚本,nvidia gb200配置教程-复制即用;gb200驱动安装

GB200 的高性能通信依赖。

jundao1997的专栏 721

详解JS中的instanceof使用及手写instanceof

instanceof 是什么? instanceof 是用来判断左侧对象是否是右侧构造函数的实例化对象,或则说左侧对象能否通过其隐式原型 **[[proto]]**在原型链上一层层向上查找到右侧函数的原型对象,即函数原型对象出现在实例对象的原型链上就返回 true。 通俗的理解: 右侧是不是左侧的爸爸、爷爷、祖宗,只要左侧对象继承自右侧函数就为 true instanceof 使用方式: object instanceof 构造函数,左侧必须为对象类型,右侧必须为函数类型。手撕instanceof, 原理

qq_40868156的博客 1万+

【ROS2】机械臂MoveIt2

navigation2 专注于移动机器人的导航与定位,处理大范围空间的底盘运动;MoveIt2 专注于机械臂的操作规划,处理多关节协同的末端执行器运动。在复合机器人(如,移动机械臂)navigation2 负责移动到目标区域,MoveIt2 负责机械臂抓取。官网:https://moveit.picknik.ai/main/index.html。

郭老二 614

【新能源汽车DCDC变换器测试优化全攻略:解决电能质量/发热/过充等核心痛点】

高压直流转12V低压的DCDC变换器是新能源汽车电源系统的核心枢纽,承担着为整车低压附件、控制器及12V蓄电池供电/补电的关键作用。在新能源汽车乘用车、商用车等不同车型实际运营中,因PDU内DC/AC等模块干扰、DCDC自身设计缺陷、整车匹配性不佳及测试验证不充分,频发12V输出电能质量差导致后端元器件烧毁、变换器发热严重、蓄电池过充/欠充、智能补电功能失效等问题,还伴随低压侧电压瞬跌/浪涌、电磁干扰超标、振动后接触不良、高温下效率骤降等行业高频故障,直接影响整车可靠性和运营安全性。本文基于国标。

CSDN-新能源汽车研发测试专业博主 1279

JavaScript中的instanceof运算符

JavaScript中的原型,原型链和instanceof运算符详解。

weixin_43263355的博客 6609

微信小程序 - 详细解决web-view公众号文章或第三方网站分享转发后打开失败,页面显示“无法打开该页面,不支持打开“、“页面不存在“报错提示,苹果IOS系统手机打开是空白页,安卓手机系统会有提示!

微信小程序,公众号文章,第三方H5网页,内嵌网站分享后打不开,web-view,页面分享,小程序里公众号文章转发后无法打开,白屏,页面空白什么都没有,不支持打开,无法打开该页面,页面不存在,业务域名配置好了还是不行,公众号和小程序已经关联,iOS端苹果真机打开空白页,安卓手机,页面分享后,用户打不开提示错误,提示页面不存在,如何解决页面提示无法打开该页面,微信小程序web-view无法打开该页面不支持打开的解决方法,无法打开该页面不支持打开,最新详细解决方案,分享之后无法打开页面,提示无法打开该页面,不支持

🏆 前端领域优质创作者 1万+

深入理解 JavaScript 的 instanceof 与继承机制:从原型链到手写实现

本文从原型链基础出发,详解 instanceof 的工作原理, Person.prototype = new Animal() 等真实代码示例,对比多种继承方式,并探讨 instanceof 在现代开发中的应用场景与局限,助你真正掌握 JS 面向对象核心。

zjy_bjyxszd的博客 857

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

JS手写instanceof实现方式

// 使用方式 function Car(color) { this.color = color this.sayColor = function () { console.log(this.color) } } // const cc = new Car('red') // console.log(cc instanceof Car) /** * 重点是分为基本数据类型和引用数据类型判断 * 引用数据类型中,需要判断对象(child)的原型链是否相等 *

冻书的博客 666

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

手写 instanceof:深入理解 JavaScript 原型与继承机制

instanceof不仅仅是一个运算符,它体现了 JavaScript 原型继承的核心思想。通过手写,我们不仅掌握了其工作原理,也加深了对原型链的理解。在实际开发中,合理使用继承模式(如组合继承),配合instanceof进行类型判断,能够显著提升代码的可维护性与健壮性。在 ES6+ 时代,虽然class语法糖让继承看起来更“传统”,但其底层依然是基于原型链。因此,无论语法如何演进,理解原型机制始终是掌握 JavaScript 面向对象编程的关键。正如那句老话:“知其然,更要知其所以然。”——手写。

jj1245_的博客 580

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

JavaScript 原型链、instanceof、new、继承、Class

JavaScript 原型链、instanceof、new、继承、Class

Lyrelion的博客 794

来,手写一个代码我看看?

来自:非常记得你https://juejin.im/post/5e24590ef265da3e152d27bc又是一年金三银四面试季了,想必很多同学已经...

祈澈菇凉 478

从‘手写instanceof’到‘封装万能getType’:深入理解TypeScript/JavaScript的类型判断原理

本文深入探讨了JavaScript和TypeScript中的类型判断原理,从手写`instanceof`到封装万能`getType`函数,详细解析了`typeof`、`instanceof`和`Object.prototype.toString`等核心机制。通过实战案例和性能优化策略,帮助开发者掌握运行时类型检查技巧,提升代码安全性和可维护性。

weixin_30252709的博客 314

JavaScript 手写题

该算法赋予每个页面[3]一个访问字段,用来记录一个页面自上次被访问以来所经历的时间 t,当须淘汰一个页面时,选择现有页面中其 t 值最大的,即最近最少使用的页面予以淘汰。而且仔细观察的话,发布订阅者模式会存在一个事件名和事件的对应关系,今天可以发布天气预报,只有订阅了天气预报的才会被通知,订阅了 KFC疯狂星期四闹钟事件 的不会被提醒。bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。

热爱可抵岁月漫长 350

死磕 36 个 JS 手写题(搞懂后,提升真的大)

死磕 36 个 JS 手写题(搞懂后,提升真的大) 为什么要写这类文章 作为一个程序员,代码能力毋庸置疑是非常非常重要的,就像现在为什么大厂面试基本都问什么 API 怎么实现可见其重要性。我想说的是居然手写这么重要,那我们就必须掌握它,所以文章标题用了死磕,一点也不过分,也希望不被认为是标题党。 作为一个普通前端,我是真的写不出 Promise A+ 规范,但是没关系,我们可以站在巨人的肩膀上,要相信我们现在要走的路,前人都走过,所以可以找找现在社区已经存在的那些优秀的文章,比如工业聚大佬写的 100 行代

牛牪犇 2996

原生 JS 实现call apply bind 等API

关于 JS 中一些重要的 api 实现, 巩固你的原生 JS 功底 1. 手写 call 方法 Function.prototype.myCall = function (context, ...args) { if (typeof context === 'object' || typeof context === 'function') { context = context || window } else { context = Object.create(null) } // 为了

qq_43778110的博客 334

2019前端面试系列——JS高频手写代码题

实现 new 方法 /* * 1.创建一个空对象 * 2.链接到原型 * 3.绑定this值 * 4.返回新对象 */ // 第一种实现 function createNew() { let obj = {} // 1.创建一个空对象 let constructor = [].shift.call(arguments) // let [constructor,...

ii窝窝头的博客 306

JavaScript 手写代码 第一期

静态方法以一个现有对象作为原型,创建一个新对象。

qq_63299825的博客 2286

【JS 手写Plan】篇1

整理一些面试常见的js手写题,冲鸭❤ Object.create() function create(obj) { function F() { } F.prototype = obj; return new F(); } /** * 1. 创建一个函数F * 2. 将obj作为F的原型对象 * 3. 返回由这个构造函数创建的实例 */ instanceOf function myInstanceof(left,right) { let prototy

金金的博客 356

前端面试手撕JS:从Promise到防抖深拷贝,高频手写题全拆解

在JavaScript工程实践中,手写代码是检验语言基础与逻辑思维最直接的方式,也是前端面试中高频出现的考察环节。从异步编程的核心Promise,到闭包应用的代表防抖与节流,再到引用类型处理的深拷贝、数组去重与扁平化,每一道手写题都对应着JS的底层机制。理解状态机、微任务队列、原型链、递归与哈希表,不仅能应对“现场编码”的考核,更能提升日常开发中对API的掌控力。本文从基础概念与原理出发,梳理高频手撕题的解题思路与边界处理,并结合浏览器事件循环、组件性能优化等真实场景,帮助开发者建立系统化的手写代码能力框架

weixin_31556767的博客 251
上一篇: TypeScript 中 typeof 的全面解析:从基础用法到高级技巧
下一篇: 队列:先进先出的线性数据结构及其应用
CbukeJ
博客等级 码龄2年 4粉丝 0原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值