JS面向对象

特性:封装、继承、多态

封装:将数据和对数据的操作集中在一起

继承:一个类型的对象可以访问另一个类型对象的属性和方法

多态:同一个方法作用于不同对象会有不同的结果
原型对象:每一个构造函数都有一个原型对象,每一个原型对象都有一个指向构造函数的指针(constructor);每一个对象实例都有指向原型对象的内部指针(__proto__,原型对象上的属性和方法都能被实例所访问。

封装:

function Person(name,age){
		var count = 10;      //私有属性
		this.name = name;   //实例属性
		this.age = age;
		ths.foo = function(){   //实例方法
			console.log(count);  //10
}
}
Person.prototype.sayHello = function(){   //原型方法
		console.log(this.name);        //name值
		console.log(count);           //报错,无法获取构造函数的私有属性
}

继承:

原型链:

①组合继承

function Person(){
		this.name = name;
		this.age = age;
}
Person.prototype.sayHello = function(){
		console.log(this.name);
}
function Male(name,age){
		Person.call(this,name,age);       //继承实例属性
		this.sex = “male”;
}
for(var I in Person.prototype){           //继承原型方法
		Male.prototype[i] = Person.prototype[i];
}
Male.prototype.sayHi = function(){
		console.log(“aaa”);
}
var male = new Male(“john”,20);
var person = new Person(“jj”,20);
male.sayHello();    //john
male.sayHi();      //aaa
person.sayHi();      //报错 person.sayHi is not a function

②寄生式组合继承

function Person(name,age){
		this.name = name;
		this.age = age;
}
Person.prototype.sayHello = function(){
		console.log(this.name);
}
function Male(name,age){
		Person.call(this,name,age);        //继承实例属性
		this.sex = “male”;
}
Male.prototype = Object.create(Person.prototype);   //继承实例方法
Male.protptype.constructor = Male;  //使实例方法指向Male
Male.prototype.sayHi = function(){
			console.log(“aaa”);
}
var male = new Male(“john”,20);
male.sayHello();           //john
console.log(male.__proto__.constructor);    //Male构造函数

③ES6中的继承

class Person{
		constructor(name,age){
			this.name = name;
			this.age = age;
}
sayHello(){
	console.log(this.name);
}
static foo(){
	console.log(“foo”);
}
}
class Male extends Person{
		constructor(name,age){
			super(name,age);   //super实现实例属性的继承,super指向父类的构造函数
}
sayHi(){
	super.sayHello();    //super指向父类的原型对象
}
static foo(){
	super.foo();       //指向父类
}
}
Var male = new Male(“john”,20);
male.sayHello();   //john
male.sayHi();     //john
Male.foo();      //foo

 

多态:

    console.log(1+2);  //3
    console.log("1"+"2");  //12

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值