在javascript中定义一个类

时间:2016-05-02 18:43:52

标签: javascript oop

在javascript中定义类的正确方法是什么?

使用class关键字。

var c = class {
constructor(){}
}

使用函数关键字。

var c = function(){
}

我看到一些文章,我认为使用class关键字是一种新方式,使用函数关键字是一种古老的方式。

2 个答案:

答案 0 :(得分:2)

简单地说:

class myClass {
    constructor(foo, bar) {
        this.foo = foo;
        this.bar = bar;
    }

    /* Whatever else */

}

这是考虑你想写ES6 ......

MDN:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes

如果是ES5,以下是https://github.com/addyosmani/es6-equivalents-in-es5#classes中有关如何解决问题的示例。

<强> ES6:

class Hello {
  constructor(name) {
    this.name = name;
  }

  hello() {
    return 'Hello ' + this.name + '!';
  }

  static sayHelloAll() {
    return 'Hello everyone!';
  }
}

class HelloWorld extends Hello {
  constructor() {
    super('World');
  }

  echo() {
    alert(super.hello());
  }
}

var hw = new HelloWorld();
hw.echo();

alert(Hello.sayHelloAll());

ES5(近似值):

function Hello(name) {
  this.name = name;
}

Hello.prototype.hello = function hello() {
  return 'Hello ' + this.name + '!';
};

Hello.sayHelloAll = function () {
  return 'Hello everyone!';
};

function HelloWorld() {
  Hello.call(this, 'World');
}

HelloWorld.prototype = Object.create(Hello.prototype);

HelloWorld.prototype.echo = function echo() {
  alert(Hello.prototype.hello.call(this));
};

var hw = new HelloWorld();
hw.echo();

alert(Hello.sayHelloAll());

答案 1 :(得分:0)

这取决于您要使用的ECMAScript标准http://www.ecmascript.org/