如何在JavaScript中定义OOP类?

时间:2010-02-08 12:05:54

标签: javascript oop

根据我的观察,我正在阅读的关于JavaScript的书说明有一个带有JavaScript的OOP?它并没有说太多,我的意思是没有解释如何定义一个类。有人可以给我一个样本片段吗?

由于

7 个答案:

答案 0 :(得分:8)

JavaScript Prototype based ,而不是基于类。

  

基于原型的编程是一种风格   面向对象编程的研究   哪些课程不存在,以及   行为重用(称为继承   在基于类的语言中)执行   通过克隆现有的过程   作为原型的对象。这个   模型也可以称为无类,   面向原型或基于实例   节目。代表团是   支持的语言功能   基于原型的编程。

答案 1 :(得分:4)

我建议this book简要,准确地解释如何使用JS的原型继承以及如何在JS中模拟经典的OO继承。

JavaScript: The good parts

答案 2 :(得分:3)

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));

答案 3 :(得分:2)

以下是几种不同的方式

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和类似的如何处理类,看看它是否适合你的需要。

答案 4 :(得分:2)

在JavaScript中没有一种标准的OOP方式。每个人都使用略有不同的类/实例系统,大多数书都捏造了这个问题。有关在JS中使用OO并选择您喜欢的方法的讨论,请参阅this question

答案 5 :(得分:1)

以下代码段可以帮助您开始使用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

示例来自:SitePoint - JavaScript Object-Oriented Programming

答案 6 :(得分:1)

在JavaScript中,一切都是对象。所以即使是一个函数也是一个对象。所以在js(少于<版本2)中,函数创建类(它们本身就是第一类对象)。转到hereherehere以便更好地了解

相关问题