W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
function Shape () {/*from www.o2fo.com*/
this.X = 0;
this.Y = 0;
this.move = function (x, y) {
this.X = x;
this.Y = y;
}
this.distance_from_origin = function () {
return Math.sqrt(this.X*this.X + this.Y*this.Y);
}
}
var s = new Shape();
s.move(10, 10);
console.log(s.distance_from_origin());
你可以隨時向你的類中添加任意數(shù)量的屬性和方法:
var s = new Shape(15, 35);
s.FillColour = "red";
聲明類的函數(shù)是它的構造函數(shù)!
默認情況下,JavaScript中的所有對象都有一個原型對象。原型對象是它們繼承屬性和方法的機制。以下代碼顯示如何使用原型創(chuàng)建繼承。更改Shape類,以便所有繼承對象也獲得X和Y屬性,以及你聲明的方法:
function Shape () {//www.o2fo.com
}
Shape.prototype.X = 0;
Shape.prototype.Y = 0;
Shape.prototype.move = function (x, y) {
this.X = x;
this.Y = y;
}
Shape.prototype.distance_from_origin = function () {
return Math.sqrt(this.X*this.X + this.Y*this.Y);
}
Shape.prototype.area = function () {
throw new Error("I don't have a form yet");
}
var s = new Shape();
s.move(10, 10);
console.log(s.distance_from_origin());
function Square() {
}
Square.prototype = new Shape();
Square.prototype.__proto__ = Shape.prototype;
Square.prototype.Width = 0;
Square.prototype.area = function () {
return this.Width * this.Width;
}
var sq = new Square();
sq.move(-5, -5);
sq.Width = 5;
console.log(sq.area());
console.log(sq.distance_from_origin());
上面的代碼生成以下結果。
你可以進一步擴展一個新的類叫Rectangle,繼承自Square類:
function Rectangle () {/*www.o2fo.com*/
}
Rectangle.prototype = new Square();
Rectangle.prototype.__proto__ = Square.prototype;
Rectangle.prototype.Height = 0;
Rectangle.prototype.area = function () {
return this.Width * this.Height;
}
var re = new Rectangle();
re.move(25, 25);
re.Width = 10;
re.Height = 5;
console.log(re.area());
console.log(re.distance_from_origin());
我們可以使用運算符instanceof來檢查繼承。
console.log(sq instanceof Square); // true
console.log(sq instanceof Shape); // true
console.log(sq instanceof Rectangle); // false
console.log(re instanceof Rectangle); // true
console.log(sq instanceof Square); // true
console.log(sq instanceof Shape); // true
console.log(sq instanceof Date); // false
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: