您的位置:首页 > Web前端 > JavaScript

js实现继承的几种方式

2018-10-03 16:54 701 查看
// 定义一个动物类
function Animal (name) {
// 属性
this.name = name || 'Animal';
// 实例方法
this.sleep = function(){
console.log(this.name + '正在睡觉!');
}
}
// 原型方法
Animal.prototype.eat = function(food) {
console.log(this.name + '正在吃:' + food);
};

function Cat(name){
Animal.call(this);
this.name = name || 'Tom';
}
(function(){
// 创建一个没有实例方法的类
var Super = function(){};
Super.prototype = Animal.prototype;
//将实例作为子类的原型
Cat.prototype = new Super();
})();
Cat.prototype.run = function(){
console.log(this.name+"正在抓老鼠");
}

// Test Code
var cat = new Cat("jeetty");
console.log(cat.name);
cat.sleep();
cat.eat('饭');
cat.run();
console.log(cat instanceof Animal); // true
console.log(cat instanceof Cat); //true

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: