avascript 是一种 prototype based programming 的语言, 有别于(java,C++)的 class based programming 继承模式。
javascript语言特点:
函数是first class object, 也就是说函数与对象具有相同的语言地位
没有类,只有对象
函数也是一种对象,所谓的函数对象
对象是按引用来传递的
javascript中的每个对象都有prototype属性,Javascript中对象的prototype属性:返回对象类型原型的引用。
function
A(a, b, c)
{
return
a*b*c;
}
console.log(A.length);
console.log(
typeof
A.constructor);
console.log(
typeof
A.call);
console.log(
typeof
A.apply);
console.log(
typeof
A.prototype);
//结果
/*3
function
function
function
object */
|
在javascript中对于任何函数都拥有这5大属性。由于prototype是一个对象,所有可以添加属性和方法,用来实现继承和其他维度的扩展。
function
Person(name, age)
{
this
.name = name;
this
.age = age;
this
.show =
function
(){
var
res =
"我是 "
+
this
.name +
" 年龄 "
+
this
.age +
"."
;
return
res;
};
}
// 给person添加几个属性
Person.prototype.gender =
"女"
;
Person.prototype.getSex =
function
(){
return
this
.gender;
};
//定义学生对象
function
Student(num){
this
.num=num;
}
Student.prototype=
new
Person(
"alice"
,23);
var
s=
new
Student(123434);
console.log(s.show());
|
//通过上看出
当查找一个对象的属性/方法时,JavaScript 会向上遍历原型链,直到找到给定名称的属性为止。
到查找到达原型链的顶部 - 也就是 Object.prototype - 但是仍然没有找到指定的属性,就会返回 undefined
这里做一个简单的介绍,如果要完全的搞清楚,你可以看看《Javascript权威之南》《javascript高级编程》《javascript精粹》