Node.js 类
2021-01-09 14:10 更新
Javascript的类都声明为函数:
function Shape () {/*from www.w3cschool.cn*/
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());
你可以随时向你的类中添加任意数量的属性和方法:
var s = new Shape(15, 35);
s.FillColour = "red";
声明类的函数是它的构造函数!
原型和继承
默认情况下,JavaScript中的所有对象都有一个原型对象。原型对象是它们继承属性和方法的机制。以下代码显示如何使用原型创建继承。更改Shape类,以便所有继承对象也获得X和Y属性,以及你声明的方法:
function Shape () {//www.w3cschool.cn
}
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.w3cschool.cn*/
}
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
以上内容是否对您有帮助:
更多建议: