五,继承
属性通过调用父类构造函数复制,方法通过原型链公用。
1> 原型链
function SuperType(){
this.property = true;
}
SuperType.prototype.getSuperValue = function(){
return this.property;
};
function SubType(){
this.subproperty = false;
}
SubType.prototype = new SuperType();
SubType.prototype.getSubValue = function(){
return this.subproperty;
}
优势:可通过instanceof和isPrototypeOf()检测
缺陷:父类的引用类型属性将被子类公用。
2> 借用构造函数
function SuperType(){
this.colors = ["red","blue","green"];
}
function SubType(){
SuperType.call(this);
}
优势:父类的所有属性和方法都被复制到子类中
缺陷:无法公用父类的方法。
3> 组合继承
function SuperType(name){
this.name = name;
this.colors = ["red","blue","green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(name, age){
SuperType.call(this, name);
this.age = age;
}
SubType.prototype = new SuperType();
SubType.prototype.sayAge = function(){
alert(this.age);
};
优势:子类从父类公用方法,复制属性。
4> 原型式继承
function object(o){
function F(){}
F.prototype = o;
return new F();
}
var person = { name : "Nicholas", friends : ["Shelby", "Court", "Van"] };
var anotherPerson = object(person);
5>寄生式继承
function createAnother(original){
var clone = object(original);
clone.sayHi = function(){
alert("hi");
};
return clone;
}
var person = { name : "Nicholas", friends : ["Shelby", "Court", "Van"]
var anotherPerson = createAnother(person);
6>寄生组合式继承
function inheritPrototype(subType, superType){
var prototype = object(superType.prototype);
prototype.constructor = subType;
subType.prototype = prototype;
}
function SuperType(name){
this.name = name;
this.colors = ["red","blue","green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
};
function SubType(name, age){
SuperType.call(this, name);
this.age = age;
}
inheritPrototype(SubType, SuperType);
SubType.prototype.sayAge = function(){
alert(this.age);
};
最佳方案。
二,变量的作用域
JavaScript没有块级作用域。
三,垃圾回收机制
尽管JavaScript拥有垃圾回收机制,但仍然需要管理内存,原则就是将不用的全局变量设置为null,而局部变量则会在离开执行环境后自动被设为null。