Node.js 類

2021-01-09 14:10 更新

Javascript的類都聲明為函數(shù):

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


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號