我更喜欢在大型项目中使用OOP,比如我现在正在做的项目。我需要在JavaScript中创建几个类,但是,如果我没有弄错的话,至少有几种方法可以做到这一点。它的语法是什么,为什么要这样做?

我希望避免使用第三方库——至少一开始是这样。 为了寻找其他答案,我找到了一篇文章《JavaScript面向对象编程,第一部分:继承- JavaScript文档》,它讨论了JavaScript中的面向对象编程。是否有更好的继承方式?


当前回答

简单的方法是:

function Foo(a) {
  var that=this;

  function privateMethod() { .. }

  // public methods
  that.add = function(b) {
    return a + b;
  };
  that.avg = function(b) {
    return that.add(b) / 2; // calling another public method
  };
}

var x = new Foo(10);
alert(x.add(2)); // 12
alert(x.avg(20)); // 15

这样做的原因是,如果您将一个方法作为事件处理程序提供,那么它可以绑定到其他东西,因此您可以在实例化期间保存该值,并在以后使用它。

编辑:这绝对不是最好的方法,只是一种简单的方法。我也在等待好的答案!

其他回答

var Animal = function(options) {
    var name = options.name;
    var animal = {};

    animal.getName = function() {
        return name;
    };

    var somePrivateMethod = function() {

    };

    return animal;
};

// usage
var cat = Animal({name: 'tiger'});

我认为你应该阅读Douglas Crockford的《JavaScript中的原型继承》和《JavaScript中的经典继承》。

来自他的页面的例子:

Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

效果吗?它将允许你以更优雅的方式添加方法:

function Parenizor(value) {
    this.setValue(value);
}

Parenizor.method('setValue', function (value) {
    this.value = value;
    return this;
});

我也推荐他的视频: 先进的JavaScript。

你可以在他的个人主页http://javascript.crockford.com/上找到更多视频 在John Reisig的书中,你可以从Douglas Crockfor的网站上找到许多例子。

//新方法使用this和new 人员(姓名){ This.name = name; 这一点。Greeting = function() { 警报('你好!I\'m ' + this.name + '.'); }; } var gee=新人员(“gee”); gee.greeting (); var gray=新人员(“灰色”); gray.greeting (); / /老方法 函数createPerson(名字){ var obj = {}; obj.name =名称; obj。Greeting = function(){ console.log("hello I am"+obj.name); }; 返回obj; } var吉塔= createPerson(“吉塔”); gita.greeting ();

var Student = (function () {
    function Student(firstname, lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.fullname = firstname + " " + lastname;
    }

    Student.prototype.sayMyName = function () {
        return this.fullname;
    };

    return Student;
}());

var user = new Student("Jane", "User");
var user_fullname = user.sayMyName();

这就是TypeScript将带有构造函数的类编译到JavaScript的方式。

以下是在javascript中创建对象的方法,这是我迄今为止使用的方法

示例1:

obj = new Object();
obj.name = 'test';
obj.sayHello = function() {
    console.log('Hello '+ this.name);
}

示例2:

obj = {};
obj.name = 'test';
obj.sayHello = function() {
    console.log('Hello '+ this.name);
}
obj.sayHello();

示例3:

var obj = function(nameParam) {
    this.name = nameParam;
}
obj.prototype.sayHello = function() {
    console.log('Hello '+ this.name);
}

例4:Object.create()的实际好处。请参阅[此连结]

var Obj = {
    init: function(nameParam) {
        this.name = nameParam;
    },
    sayHello: function() {
        console.log('Hello '+ this.name);
    }
};
var usrObj = Object.create(Obj);  // <== one level of inheritance

usrObj.init('Bob');
usrObj.sayHello();

例5(自定义Crockford's Object.create):

Object.build = function(o) {
   var initArgs = Array.prototype.slice.call(arguments,1)
   function F() {
      if((typeof o.init === 'function') && initArgs.length) {
         o.init.apply(this,initArgs)
      }
   }
   F.prototype = o
   return new F()
}
MY_GLOBAL = {i: 1, nextId: function(){return this.i++}}  // For example

var userB = {
    init: function(nameParam) {
        this.id = MY_GLOBAL.nextId();
        this.name = nameParam;
    },
    sayHello: function() {
        console.log('Hello '+ this.name);
    }
};
var bob = Object.build(userB, 'Bob');  // Different from your code
bob.sayHello();

保持答案与ES6/ ES2015更新

类是这样定义的:

class Person {
    constructor(strName, numAge) {
        this.name = strName;
        this.age = numAge;
    }

    toString() {
        return '((Class::Person) named ' + this.name + ' & of age ' + this.age + ')';
    }
}

let objPerson = new Person("Bob",33);
console.log(objPerson.toString());