一、类和对象
1, JavaScript对象分为三类:本地对象,内置对象,宿主对象。
本地对象有15种:Object Function Array String Number Boolean Date RegExp Error EvalError RangeError
RrefenceError SyntaxError TypeError UIRError
内置对象有2种:Global Math
宿主对象有N中:所有DOM和BOM对象
2,如何在JavaScript中定义一个类和对象
方法一:原始方法
var car = new Object; car.name = "BMW"; car.color = "blue"; car.showColor = function(){ alert(this.color); }
car.showColor();
这是最原始的方法,但是有一个缺点就是,如果要创建多个实例,代码会很长。
方法二:工厂方法
function createCar(name,color){ var oCar = new Object; oCar.name = name; oCar.color = color; oCar.showColor = function(){ alert(this.color); } return oCar; }
工厂方法解决了创建多个函数的缺点,但是在语义上不符合传统面向对象的语言的构造函数。
方法三:构造函数方式
function Car(name,color){ this.name = name; this.color = color; this.showColor = function(){ console.log(this.color); } } var car1 = new Car("bmw","blue"); car1.showColor();
该方法类似于Java的构造函数,唯一的缺点是无法创造静态变量和方法。
方法四:原型方式
function Car() { } Car.prototype.color = "blue"; Car.prototype.doors = 4; Car.prototype.mpg = 25; Car.prototype.showColor = function() { alert(this.color); }; var oCar1 = new Car(); var oCar2 = new Car();
方法五:混合方式
function Car(sColor,iDoors,iMpg) { this.color = sColor; this.doors = iDoors; this.mpg = iMpg; this.drivers = new Array("Mike","John"); } Car.prototype.showColor = function() { alert(this.color); }; var oCar1 = new Car("red",4,23); var oCar2 = new Car("blue",3,25); oCar1.drivers.push("Bill"); alert(oCar1.drivers); //输出 "Mike,John,Bill" alert(oCar2.drivers); //输出 "Mike,John"
这是比较常用的方法。
方法六:动态原型方法
function Car(sColor,iDoors,iMpg) { this.color = sColor; this.doors = iDoors; this.mpg = iMpg; this.drivers = new Array("Mike","John"); if (typeof Car._initialized == "undefined") { Car.prototype.showColor = function() { alert(this.color); }; Car._initialized = true; } }
二:继承
1.原型继承,关键是子类的原型指向了一个父类的对象。代码如下,
function Animal(){ this.gender = "male"; }; function Dog(){ this.name = "huang"; }; Dog.prototype = new Animal(); var dog1 = new Dog(); console.log(dog1.gender);//"male"
2.原型继承的缺点就是父类属性是对象的情况,如下代码,
function Animal(){ this.gender = "male"; this.catlog = ["a","b","c"]; }; function Dog(){ this.name = "huang"; }; Dog.prototype = new Animal(); var dog1 = new Dog(); dog1.catlog.push("d"); var dog2 = new Dog(); console.log(dog2.catlog);// ["a", "b", "c", "d"]
dog1的改动和影响dog2,,因为Dog实例的prototype现在是一个Animal实例,所以dog1和dog2两个实例共享prototype中的属性。于是就出来了组合继承的方式,通过call来执行父类的构造函数
3.组合继承
function Animal(gender){ this.gender = gender; this.catlog = ["a","b","c"]; }; function Dog(gender){ Animal.call(this,gender); this.name = "huang"; }; Dog.prototype = new Animal(); var dog1 = new Dog("asdf"); console.log(dog1.gender); dog1.catlog.push("d"); console.log(dog1.catlog);//["a", "b", "c"] var dog2 = new Dog(); console.log(dog2.catlog);// ["a", "b", "c","d"]