function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.sayHello = function() {
console.log('Hello, my name is ' + this.name);
}
var person = new Person('John', 25);
person.sayHello(); // 输出:Hello, my name is John
function Animal(name) {
this.name = name;
}
Animal.prototype.sayName = function() {
console.log('My name is ' + this.name);
}
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.sayBreed = function() {
console.log('I am a ' + this.breed);
}
var dog = new Dog('Max', 'Labrador');
dog.sayName(); // 输出:My name is Max
dog.sayBreed(); // 输出:I am a Labrador
function Shape() { }
Shape.prototype.area = function() {
return 0;
}
function Square(length) {
this.length = length;
}
Square.prototype = Object.create(Shape.prototype);
Square.prototype.constructor = Square;
Square.prototype.area = function() {
return this.length * this.length;
}
function Circle(radius) {
this.radius = radius;
}
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
Circle.prototype.area = function() {
return Math.PI * this.radius * this.radius;
}
var square = new Square(5);
var circle = new Circle(3);
console.log(square.area()); // 输出:25
console.log(circle.area()); // 输出:28.274333882308138
本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com