Javascript是一种基于对象(object-based)的语言
1.ES5封装
function cat( name, age){
this.name = name;
this.age = age;
}
cat.prototype.type = '猫科动物';
cat.prototype.eat = function() {console.log('吃老鼠')};
var cat1 = new cat('米老鼠','20');
console.log(cat1.eat()); //吃老鼠
2.ES5继承
function Women(){
this.sex = 'women';
}
function Girl(name,age){
Women.apply(this,arguments);
this.name = name;
this.age = age;
}
var xh = new Girl('小花',20);
console.log(xh.sex); // women
// 第二种
Girl.prototype = new Women();
Girl.prototype.constructor = Girl;
var xh = new Girl('小花',20);
console.log(xh.sex); // women
3.ES6封装
class Person{ //方法之间不能有逗号
constructor(x,y){
this.x = x;
this.y = y;
}
say(){
console.log('hello');
}
}
var p = new Person('xx','aa');
4.ES6继承
class Person{ //方法之间不能有逗号
constructor(x,y){
this.x = x;
this.y = y;
}
say(){
console.log('hello');
}
}
class Men extends Person{
constructor(x,x,sex){
super(x,y); // 子类必须用super来继承父类的this
this.sex = sex;
}
eat(){
console.log('吃东西');
}
}
var xm = new Men('x1','y1','男');
console.log(xm.x); // x1