JavaScript面向对象特性

面向对象三大特性

封装(隐藏捏不得实现细节,只对外开放操作接口)
继承(一个对象继承另一个对象成员,从而在不改变另一个对象的前提下进行扩展)
多态(同一个操作作用于不同的对象,会产生不同的执行结果)

面向对象的举例说明

函数的创建

//这里的函数名在面向对象里叫做类
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());     //输出咯咯咯
         
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值