1.实例属性、实例方法与类属性、类方法
function circle(r){
this.redius = r; //redius属性实例属性,即该类型的每个实例对象都具有copy该属性
}
circle.PI = 3.14; //P为circle类的一个类属性,跟实例无关
circle.prototype.area = function (){ return circle.PI*this.redius*this.redius }; //area是一个实例方法,里面引用类属性PI
circle.init = function (){ return new circle(1);}init()为类方法,此方法用于创建一个半径为1的圆形
实例属性、实例方法类试java中的非静态属性或函数
类属性、类方法类似java中的静态属性或函数
2.类继承
动物类:
function animal(){
this.type = "animal";
}
猫类:
function cat (name,age){
this.name = name;
this.age = age;
}
如何让cat继承animal类呢?
1.构造函数绑定模式:
function cat(name,age){
animal.call(this,[arguments]) //arguments为传递的参数数组,this参数为调用此函数的对象,这里是cat
this.name = name;
this.age = age;
}
var c = new car('tom',19);
console.log(c.type);
2.原型继承模式
cat.prototype = new animal();//给cat的原身prototype重新初始化
cat.prototype.constuctor = cat;//上面已经将原身prototype重新赋值,原身prototype的constructor就不存在,所以这里需要重新指定constructor值,这里是cat, 否则后面的继承链出问题
var c = new car('tom',19);
console.log(c.type);
总之编程时候要遵守一点如果重新赋值o.prototype的值:
o.prototype={};
接下来务必要给o.prototype.constructor赋值:
o.prototype.constructor = o;