javascript 语言

本文探讨了JavaScript中对象的本质,即Hashtable,并介绍了如何通过new关键字创建对象以及prototype链的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ruby语言的根本就是 Object,Module, Class这三个对象。而且Module,Class本身就是对象。
在任何的Object中,方法和属性是分别存储在不同的hash表里的。

而对于javascript 其根本就是一个hashtable和function。
除了一些基本类型以外(bollean, number, string),其他的东西都是Object, Object就是一个hashtable。
所以, a = {}, 和a = new Object() 是一样的。
Object中的hashtable存放变量和方法。 也就是说, 变量和方法都是存储在Object的同一个hashtable中的。
为了让function 也可以存储到Object hash中,function实际上也是一个Object。
所以如下代码是一样的。
1.
Function father(){}
father.name = "abc"
father.speak = function (){}
2.
father = new Object()
father.name = "abc"
father.speak = function (){}

为了使Object通过new 的方式生成一个新的Object,new 关键字加function 就使得function 变成了一个构造函数。返回的是一个新的Object,如下。

function Father(name, speak) {
this.name = name;
this.speak = speak;
}

fatherObj = new Father("john", function(words){
alert(words);
})

fatherObj.speak("hello!");

另外,每一个Object中都存在一个叫__proto__的link,指向object的父亲的prototype。
而prototype可以是object,也可以是function。这样就构成了prototype的chain。

function Father(){
}
Father.prototype.fatherSay = function(){
alert("from father");
}
Father.spit = function(){alert("spit")}
function Mother(){
}

Mother.prototype = Father
son = new Mother();
son.spit(); //right
son.fatherSay //not found

上面代码调用的方法查找过程:
1.查找son里有没有spit方法
2.查找son.protype里有没有spit方法
2.查找Mother.prototype里有没有spit
3.如果Mother.prototype中没有spit,接着要查找Mother.__proto__指向的Object.prototype.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值