代码之家  ›  专栏  ›  技术社区  ›  Ben

如何在Javascript中创建OOP类

  •  1
  • Ben  · 技术社区  · 14 年前

    我很犹豫是否使用任何一个教程,因为我知道这些教程最终会是什么,教你做事情的坏方法。我想用Javascript设置一个类,这样我就可以

    var vehicle = new Vehicle(el);
    var model = vehicle->getModel();
    

    这些函数将读取HTML并获取和管理页面上的元素。我现在正在做一个像。。。

    var model = function () {
     return {
      getName: function () {
    
      },
      getVehicleCount: function () {
    
      },
      incrementCount: function (id) {
       console.log(x);
      }
     }
    }();
    

    我还在学习Javascript的课程。。。我希望能够为所有方法都将使用的元素传递类a节点,但我不确定我做得是否正确。。。

    3 回复  |  直到 14 年前
        1
  •  5
  •   Paul D. Waite    12 年前

    this 关键字,然后用 new 操作员:

    function Foo (id) { // By convention, constructor functions start with a capital letter
        this.id = id;
    }
    
    var foo1 = new Foo(1);
    var foo2 = new Foo(2);
    

    Foo.prototype = {
        getId: function () {
            return this.id;
        }
    }
    

    getId 所有人都可以使用这个函数 Foo 物体。但是,正如前面所说的,JavaScript中没有类,因此您将使用其他构造来生成不同的结果。

    我强烈推荐Douglas Crockford的视频,他在视频中解释了JavaScriptoo的许多本质。会谈内容如下:

    http://developer.yahoo.com/yui/theater/

    Douglas Crockford高级JavaScript

        2
  •  1
  •   Pablo Mescher    12 年前

    尽管JavaScript中没有类,但是可以创建构造函数。构造函数通过将方法绑定到对象原型来工作。有几种方法可以做到这一点,每种方法都有优点和缺点。我个人更喜欢最直接的方式,即在“this”后面附加方法:

    var Constructor = function() {
    
      //object properties can be declared directly
      this.property = "value";
    
      //to add a method simply use dot notation to assign an anonymous function to an object
      //property
      this.method = function () {
        //some code
      }
    
      //you can even add private functions here. This function will only be visible to this object methods
      function private() {
        //some code
      }
      //use return this at the end to allow chaining like in var object = new Constructor().method();
      return this; 
    
    }
    
        3
  •  0
  •   jwueller    14 年前