javascript-firstclass,继承和多态

First-class

function Car() {
  var self = this;
  self.speed = 0;
  self.start = function() {
  console.log("Car started.");
  }
  self.accelerate = function() {
  self.speed = self.speed + 10;
  console.log("Speed is now:"+self.speed+ " mph");
  }
  self.applyBrakes = function() {
  self.speed = 0;
  console.log("Brakes applied.");
  }
}

使用继承和多态创建复杂对象-使用关键字 prototype

function Car() {
var self = this;
self.type = "Car"
self.go = function() {
console.log("Going...");
};
};
Toyota = function() {};
Toyota.prototype = new Car();
Toyota.prototype.constructor = function() {
var self = this;
self.type = "Toyota";
self.go = function() {
console.log("A Toyota car is going...");
}
};
Toyota.prototype.isJapaneseCar = true;
var t = new Toyota();
console.log(t instanceof Toyota);
console.log(t instanceof Car);


使用Prototype库实现继承-Prototype(www.prototypejs.org)

var Car = Class.create({
initialize: function() {
this.type = "Car";
},
go: function() {
console.log("Going...");
}
});
var Toyota = Class.create(Car, {
initialize: function() {
this.type = "Toyota";
this.isJapaneseCar = true;
},
go: function() {
console.log("A Toyota car is going...");
}
});


当使用Prototype库调用任何父对象函数时,必须在参数列表的开始处添加$super$super对象是与父函数关联,而不是与父对象关联。子对象的go函数仅能够显示调用父对象的go函数,如果是其他重载的父函数,那么是隐式调用

var Toyota = Class.create(Car, {
initialize: function() {
this.type = "Toyota";
this.isJapaneseCar = true;
},
go: function($super) {
$super();
console.log("A Toyota car is going...");
}
});


输出:

Going...

A Toyota car is going...

你可能感兴趣的:(WEB前端)