根据我的观察,我正在阅读的关于JavaScript的书说明有一个带有JavaScript的OOP?它并没有说太多,我的意思是没有解释如何定义一个类.有人可以给我一个样本片段吗?
谢谢
JavaScript是基于Prototype而不是基于类的.
基于原型的编程是一种面向对象的编程风格,其中不存在类,并且通过克隆用作原型的现有对象的过程来执行行为重用(在基于类的语言中称为继承).该模型也可称为无类,面向原型或基于实例的编程.委托是支持基于原型的编程的语言功能.
以下代码片段可以帮助您开始使用 JavaScript 的无类、基于实例的对象:
function getArea() {
return (this.radius * this.radius * 3.14);
}
function getCircumference() {
var diameter = this.radius * 2;
var circumference = diameter * 3.14;
return circumference;
}
function Circle(radius) {
this.radius = radius;
this.getArea = getArea;
this.getCircumference = getCircumference;
}
var bigCircle = new Circle(100);
var smallCircle = new Circle(2);
alert(bigCircle.getArea()); // displays 31400
alert(bigCircle.getCircumference()); // displays 618
alert(smallCircle.getArea()); // displays 12.56
alert(smallCircle.getCircumference()); // displays 12.56
Run Code Online (Sandbox Code Playgroud)
示例来自:SitePoint - JavaScript 面向对象编程