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

我希望避免使用第三方库——至少一开始是这样。 为了寻找其他答案,我找到了一篇文章《JavaScript面向对象编程,第一部分:继承- JavaScript文档》,它讨论了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());

其他回答

我认为你应该阅读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的网站上找到许多例子。

代码高尔夫@liammclennan的答案。

var Animal = function (args) { 返回{ 名称:args.name, getName:函数{ 返回this.name;//成员访问 }, callGetName:函数(){ 返回this.getName ();//方法调用 } }; }; var cat =动物({名字:'老虎'}); console.log (cat.callGetName ());

MooTools(我的面向对象工具)以类的思想为中心。您甚至可以通过继承来扩展和实现。

一旦掌握了它,就会产生可重用的强大javascript。

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的方式。

//新方法使用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 ();