[英]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.