Function与Object
Function与Object
JavaScript
中内置了两个顶级对象Function
、Object
,Object
是所有对象的基类,而所有的构造函数同时又是Function
对象的实例。
Object#
JavaScript
中的所有对象都来自Object
,所有对象从Object.prototype
继承方法和属性,尽管它们可能被覆盖,例如其他构造函数在原型中实现自己的toString()
方法。Object
原型对象的更改将传播到所有对象,除非这些受到更改的属性和方法沿原型链被覆盖。
// 定义三个对象
var a = function(){} // 构造函数对象
var b = new Array(1); // 数组对象
var c = new Number(1); // 数字对象 // 包装对象
// 检查原型链
console.log(a.__proto__.__proto__ === Object.prototype); // true
console.log(b.__proto__.__proto__ === Object.prototype); // true
console.log(c.__proto__.__proto__ === Object.prototype); // true
// 拆分指向
console.log(a.__proto__ === Function.prototype); // true
console.log(Function.prototype.__proto__ === Object.prototype); // true
console.log(b.__proto__ === Array.prototype); // true
console.log(Array.prototype.__proto__ === Object.prototype); // true
console.log(c.__proto__ === Number.prototype); // true
console.log(Number.prototype.__proto__ === Object.prototype); // true
// 使用instanceof 实际也是检测原型链
// instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上
console.log(a instanceof Object); // true
console.log(b instanceof Object); // true
console.log(c instanceof Object); // true
Function#
JavaScript
中的所有的构造函数都继承自Function
,包括Object
构造函数,Function
构造函数也继承于自己,当然Function
也是继承于Object.prototype
,可以说是先有的Object.prototype
, Object.prototype
构造出Function.prototype
,然后Function.prototype
构造出Object
和Function
。
// 构造函数对象
var a = function(){} // 构造函数对象
// 检查原型链
console.log(a.__proto__ === Function.prototype); // true
console.log(Object.__proto__ === Function.prototype); // true
console.log(Function.__proto__ === Function.prototype); // true
console.log(Function.prototype.__proto__ === Object.prototype); // true
// 使用instanceof
console.log(a instanceof Function); // true
console.log(Object instanceof Function); // true
console.log(Function instanceof Function); // true
总结#
- 一切对象都继承于
Object
,都是从Object.prototype
继承方法和属性。 - 一切构造函数包括
Object
与Function
,都继承于Function
,最终继承于Object
。
每日一题#
https://github.com/WindrunnerMax/EveryDay
参考#
https://www.cnblogs.com/tiancai/p/7463252.html
https://www.cnblogs.com/yf2196717/p/10989466.html
https://www.cnblogs.com/ioveNature/p/6880176.html
https://www.cnblogs.com/tiffanybear/p/11320651.html
https://blog.csdn.net/backee/article/details/83378772
https://blog.csdn.net/weixin_34237596/article/details/88026745
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理