面向对象

JavaScript学习之面向对象_代码示例JavaScript学习之面向对象_代码示例_02

JavaScript学习之面向对象_面向对象_03

JavaScript的继承机制

JavaScript学习之面向对象_代码示例_04JavaScript学习之面向对象_javascript_05

代码示例:

<script>
//prototype
function Person(name ,age){
this.name = name;
this.age = age;
this.info = function (){
document.write("姓名:"+this.name+"<br>");
document.write("年龄:"+this.age+"<br>");
}
}
var p1 = new Person("法外狂徒张三",29);
p1.info();
Person.prototype.walk = function(){
document.write(this.name+"溜达"+"<br>");
}
document.writeln("<hr>");
var p2 = new Person("leegang" , 30);
p2.info();
document.writeln("<hr>");
p2.walk();
p1.walk();
</script>

JavaScript学习之面向对象_javascript_06

JavaScript学习之面向对象_面向对象_07JavaScript学习之面向对象_面向对象_08

JavaScript学习之面向对象_代码示例_09

构造器实现伪继承

JavaScript学习之面向对象_面向对象_10JavaScript学习之面向对象_面向对象_11

使用apply或者call实现伪继承

JavaScript学习之面向对象_代码示例_12

代码示例:

<script>
//prototype
function Person(name ,age){
this.name = name;
this.age = age;

}
Person.prototype.sayHello = function(){
console.log(this.name+"正在打招呼");
}
var p1 = new Person("法外狂徒张三",29);
p1.sayHello();
function student(name,age,grade){
Person.call(this,name,age);
this.grade = grade;
}
student.prototype = new Person();
student.prototype.intro = function(){
console.log("%s是个学生,读%d年级",this.name,this.grade);
}
var stu = new student('李四',34,5);
var stu2 = new student('王五',33,4);
console.log(stu instanceof student);
console.log(stu instanceof Person);
stu.intro();
stu2.intro();
stu.sayHello();
stu2.sayHello();
</script>

JavaScript学习之面向对象_面向对象_13

JavaScript学习之面向对象_javascript_14

使用call方法继承构造方法,使用prototype属性来继承类的其他方法。

继承代码示例:

script>
function Animal (sex,age){
this.sex = sex;
this.age = age;
}
Animal.prototype.intro = function(){
console.log("性别:"+this.sex+",年龄:"+this.age);
}
function Dog(kind,sex,age){
this.kind = kind;
Animal.call(this,sex,age);
}
Dog.prototype = new Animal();
Dog.prototype.voice = function (){
console.log(this.kind+"叫的声音是:汪汪汪");
}
function Cat(kind,sex,age){
this.kind = kind;
Animal.call(this,sex,age);
}
Cat.prototype = new Animal();
Cat.prototype.voice = function (){
console.log(this.kind+"叫的声音是:嗷嗷嗷");
}
var d = new Dog("哈士奇","公",12);
d.intro();
d.voice();
var c = new Cat("波斯猫","母",5);
c.intro();
c.voice();
</script>

JavaScript学习之面向对象_代码示例_15

创建对象

JavaScript学习之面向对象_面向对象_16JavaScript学习之面向对象_javascript_17JavaScript学习之面向对象_面向对象_18JavaScript学习之面向对象_javascript_19