這是在javascript中定義類的正確方法嗎?在javascript中定義一個類
使用class關鍵字。
var c = class {
constructor(){}
}
或者
使用function關鍵字。
var c = function(){
}
我看到一些文章,我認爲使用類關鍵字是一種新的方式,並使用功能關鍵字是老樣子。
這是在javascript中定義類的正確方法嗎?在javascript中定義一個類
使用class關鍵字。
var c = class {
constructor(){}
}
或者
使用function關鍵字。
var c = function(){
}
我看到一些文章,我認爲使用類關鍵字是一種新的方式,並使用功能關鍵字是老樣子。
只需進入:
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());
這取決於您要使用的ECMAScript標準,http://www.ecmascript.org/
第二個就是一個函數,而第一個似乎是一個錯誤? – adeneo
如果您打算支持大多數主流瀏覽器(例如IE11,Windows 7上最新版本的IE),請不要使用'class'。這不是很好的支持。它是通過ECMAScript 6引入的。 – blex
閱讀[MDN上的類](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),它們是新的,並且不支持所有瀏覽器尚未 – adeneo