JS面向对象三大特性

首先对象的声明语法
1.通过Object

var object = new Object();
//动态添加属性。方法
object.name='test';
object.method = function(){}

2.对象字面量

var object = {
    name:'test',
    method:function(){}
}

3.构造函数

function Object(name){
    this.name = name,
    this.method = function(){}
}
//实例化
var  o = new object(name);
面向对象三大特性 封装,继承,多态

1.封装:将一些属性或方法封装起来,使外部无需关心内部是怎样运行,直接调用接口即可
当你需要隐藏一些属性和方法时,就可以将这些属性和方法封装起来,然后通过一个外部可以调用的接口进行调用。

function Person(name,age,sex){
		this.name = name;//公有属性
		this.age = age;
		var sex = sex;//私有属性
		function test(){
			console.log('test')
		}//私有方法
	}
    Person.prototype.walk=function(){
    	console.log('走');
    }//共有方法

   var man = new Person('xiaoming',13,'男');
   // man.test();//私有方法外部无法访问
   console.log(man.sex)//undifind
   // man.walk();//访问共有方法

2.继承
“子承父业”,实现代码重用通过prototypecall实现组合继承

function Person(name,age,sex){
		this.name = name;
		this.age = age;
		this.sex = sex;
	}//定义一个“人”类

	Person.prototype.method=function(){
		console.log(this.name);
	}

	function Student(name,age,sex,score){
		Person.call(this,name,age,sex);//通过call改变this指向,继承属性
		this.score = score;
	}//学生类
	Student.prototype = new Person();//通过原型,继承方法
	Student.prototype.constructor=Student;//手动改变构造函数

	var a = new Student('zs',14,'男',90);
	console.log(a);
	a.method();

在这里插入图片描述
3.多态:顾名思义多种状态,我的理解是多个对象调用同一个接口返回不同的结果
即将“做什么” 和”谁来做“区分开。
如下模拟多态。

var Sound = function(animal){
		if(animal instanceof Dog){
			//通过有Dog构造函数创建
			console.log('汪汪汪');
		}else if(animal instanceof Duck){
			//如果是由Duck构造函数创建
			console.log('嘎嘎嘎');
		}
	}
	var Duck = function(){};
	var Dog = function(){};

	Sound(new Duck());
	Sound(new Dog());

调用不同的对象会返回不同的结果
在这里插入图片描述
这里已经实现多态的定义了,但是如果我们还要增加一个对象,我们会不断修改Sound函数。
我们可以借助原型对象优化代码
如下

var Sound = function(animal){
		animal.aSound();
	}
	var Duck = function(){};
	Duck.prototype.aSound=function(){
		console.log('嘎嘎嘎');
	}

	var Dog = function(){};
	Dog.prototype.aSound = function(){
		console.log('汪汪汪');
	}

	var Bird = function(){};
	Bird.prototype.aSound = function(){
		console.log('叽叽叽');
	}
	Sound(new Duck());
	Sound(new Dog());
	Sound(new Bird());

在这里插入图片描述
将方法绑定该对象的原型对象上,我们在添加新对象时不用修改Sound函数

发布了88 篇原创文章 · 获赞 2 · 访问量 2996

猜你喜欢

转载自blog.csdn.net/weixin_45143481/article/details/104529709