面向对象三大特性
封装(隐藏捏不得实现细节,只对外开放操作接口)
继承(一个对象继承另一个对象成员,从而在不改变另一个对象的前提下进行扩展)
多态(同一个操作作用于不同的对象,会产生不同的执行结果)
面向对象的举例说明
函数的创建
//这里的函数名在面向对象里叫做类
function Create(n,s){
//var obj = new Object();
//obj叫做实例,同时也是对象,面向对象写法中系统会自动创建一个obj空对象
//对象属性
this.name = n;
this.sex = s;
//this指针在这里指的就是这个对象
//对象方法
this.showName = function(){
alert(n);
this.showSex = function(){
alert(s);
}
//返回对象,
//同样,面向对象中系统会自动帮我们返回obj(即this)
//retrun obj;
//return this;
}
- 封装
function hello(){
var a = 'hello';
alert(a);
}
- 面向对象和继承
function Person(firstName){
this.firstName = firstName;
}
Person.prototype.walk = function(){
alert(" I'm walking in" );
}
Person.prototype.sayHello = function(){
alert(" Hello,l'm "+this.firstName);
}
function Student(firstName,subject){
Person.call(this.firstName);
this.subject = subject;
}
Student.prototype = Object.creat(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.sayHello = function(){
console.log("Hello,l'm "+this.firstName+"l'm studtying"+this.object);
}
Student.prototype.sayGoodbye = function(){
console.log("goodbye");
//测试实例
var s1 = new Student("Tom","applied physics");
s1.sayHello();
s1.walk();
s1.sayGoodbye();
- 多态
var makeSound = function(animal){
if(animal instanceof Duck){
console.log("嘎嘎嘎“);
}else if(animal instanceof Chicken){
console.log("咯咯咯");
}
};
var Duck = function(){};
var Chicken = function(){}:
makeSound( new Duck()); //输出嘎嘎嘎
makeSound( new Chicken()); //输出咯咯咯