论坛首页 综合技术论坛

javascript 语言

浏览 1190 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-10-07  
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.

论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics