js 类
一、类的三种定义方式
1.1 通过字面量的方式创建一个对象
var student = { name: 'jmz', age:12, get_info:function(){ console.log(this.name+';'+this.age) } }; student.get_info(); // student 创建之初就是一个对象
1.2 创建一个空对象
var school = new Object(); school.name = "天山小学"; school.addr = '天山路122号'; console.log(school.addr);
1.3 通过构造函数来创建对象(推荐使用此方法创建)
function teacher(name,age){ // 私有化(封装) var school = '上海实验小学'; //这个就是类私有属性 var get_school = function(){ // 这是私有方法 return school; }; this.name = name; // public,公有方法 this.age = age; this.get_info = function(){ console.log(this.name +':'+this.age); console.log(get_school()) }; } var wdx =new teacher('wangdaxian',34); wdx.get_info()
二、类的继承
请先看如下的两个构造函数
function dog(){ this.animal = '狗'; this.voice = '汪汪汪'; this.speak = function(){ console.log(this.voice); }; this.eat = function(){ console.log('eat ....') }; } function cat(){ this.animal = "猫"; this.voice = "喵~"; this.speak =function(){ console.log(this.voice); }; this.eat = function(){ console.log('eat ....') } } var dog_A =new dog(); var cat_A =new cat(); dog_A.speak(); cat_A.eat();
可以看出上面的两个构造函数有相同的代码的部分(红色部分),如果每一次的都重写相同的代码,就会造成资源的不必要的浪费。
因此在javascript里边的继承,主要是原型继承,一个构造函数继承另外一个对象,通过这个构造函数实例化出来的对象,除了本身拥有的属性外,还会拥有继承过来的对象的属性特点。
/* animal = { speak:function(){ console.log(this.voice); }, eat:function(){ console.log('eat ....'); } };*/ // 原型链继承 function animal(){ this.speak =function(){ console.log(this.voice); }; this.eat = function(){ console.log('eat ....'); }; } function dog(){ this.animal = '狗'; this.voice = '汪汪汪'; } // dog.prototype = animal; dog.prototype = new animal(); function cat(){ this.animal = "猫"; this.voice = "喵~"; } // cat.prototype = animal; cat.prototype = new animal(); var dog_A =new dog(); var cat_A =new cat(); dog_A.speak(); cat_A.eat();
类的继承本文推荐:https://www.cnblogs.com/humin/p/4556820.html

浙公网安备 33010602011771号