• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
smileyqp
https://github.com/smileyqp
博客园    首页    新随笔    联系   管理    订阅  订阅

(十五)关于继承

ES5中继承的实现:
//ES5中的思路是将子类的原型设置成为父类的原型
function Super(){
	Super.prototype.getNum = function(){
		return 1;
	}
}
function Sub(){

}

	let s = new Sub();
	Sub.prototype = Object.create(Super.prototype,{
		constructor:{
			value:Sub,
			writeable:true
		}
	})
另外案例:
// Shape - 父类(superclass)
function Shape() {
  this.x = 0;
  this.y = 0;
}

// 父类的方法move
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - 子类(subclass)
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// 子类续承父类;子类的prototype指向父类的prototype

Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

//实例化子类对象
var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?',
  rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?',
  rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'
Object.create()方法创建一个新对象,其作用是使用现有的对象来提供新创建的对象的__proto__,语法:

Object.create(proto[, propertiesObject])

ES6中直接用class … extends即可
class MyDate extends Date(){
	test(){
		return this.getTime();	
	}
}
let myDate = new MyDate();
myDate.test();
posted @ 2019-09-17 11:30  smileyqp  阅读(80)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3