[英]How do you define an OOP class in JavaScript?
根据我的观察,我正在阅读的关于 JavaScript 的书指出 JavaScript 存在 OOP? 它没有说明太多,我的意思是没有解释如何定义一个类。 有人可以给我一个示例片段吗?
谢谢
JavaScript 是基于原型的,而不是基于类的。
基于原型的编程是一种面向对象的编程风格,其中不存在类,行为重用(在基于类的语言中称为继承)是通过克隆作为原型的现有对象的过程来执行的。 这种模型也可以称为无类、面向原型或基于实例的编程。 委托是支持基于原型的编程的语言特性。
我推荐这本书,以简洁、准确地解释如何使用 JS 的原型继承以及如何在 JS 中模拟经典的 OO 继承。
javascript 中的任何函数都可以用来创建一个对象:
例子:
function MyPoint(x, y) {
this.x = x;
this.y = y;
this.distanceTo = getDistance;
}
function getDistance(p) {
var dx = this.x-p.x;
var dy = this.y-p.y;
return Math.sqrt(dx*dx + dy*dy);
}
var p0 = new MyPoint(1, 2);
var p1 = new MyPoint(2, 3);
window.alert('The distance is ' + p0.distanceTo(p1));
以下代码片段可以帮助您开始使用 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
这里有几种不同的方式
if (typeof FFX == "undefined") {
FFX = {};
}
//Static class
FFX.Util = ({
return {
method:function(){
}
})();
FFX.Util.method();
//Instance class
FFX.Util2 = ({
// private method
var methodA=function(){
alert("Hello");
};
return {
method:function(){
//Call private method
methodA();
}
});
var x= new FFX.Util();
x.method();
其它的办法
function MyClass(){
}
/* privileged functions */
MyClass.prototype.hello = function(){
alert("Hello");
}
您还可以看到 jquery、prototype 等如何处理类,看看这是否适合您的需要。
在 JavaScript 中没有一种标准的 OOP 方法。 每个人使用的类/实例系统都略有不同,而且大多数书籍都掩盖了这个问题。 请参阅此问题以讨论在 JS 中使用 OO 的方法并选择您最喜欢的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.