ES6——class
生活随笔
收集整理的這篇文章主要介紹了
ES6——class
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
class Point{
constructor(x,y){
this.x = x;
this.y = y;
}
toString(){
return this.x + this.y;
}
}
console.log(typeof Point);//function,說明類的數據類型本身就是函數,類本身指向構造函數
var a = new Point(1,2);//只有x,y,并沒有constructor,__proto__中有constructor,說明類的所有方法和屬性都定義在了類的prototype屬性上面
console.log(a)//1,2
console.log(a.toString())//3,在類的實例上調用方法,實際上是在調用原型上的方法
//類和模塊的內部,默認就是嚴格模式,所以不需要使用use strict指定運行模式。只要你的代碼寫在類或模塊之中,就只有嚴格模式可用。
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function
//類相當于實例的原型,所有在類中定義的方法,都會被實例繼承。如果在一個方法前,加上static關鍵字,就表示該方法不會被實例繼承,而是直接通過類來調用,這就稱為“靜態方法”。
class Foo {
static bar () {
this.baz();
}
static baz () {
console.log('hello');
}
baz () {
console.log('world');
}
}
Foo.bar() // hello
//如果靜態方法包含this關鍵字,這個this指的是類,而不是實例。
//上面代碼中,靜態方法bar調用了this.baz,這里的this指的是Foo類,而不是Foo的實例,等同于調用Foo.baz。另外,從這個例子還可以看出,靜態方法可以與非靜態方法重名。
class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();//子類B的構造函數之中的super(),代表調用父類的構造函數
}
}
//super雖然代表了父類A的構造函數,但是返回的是子類B的實例,即super內部的this指的是B
new A() // A
new B() // B
constructor(x,y){
this.x = x;
this.y = y;
}
toString(){
return this.x + this.y;
}
}
console.log(typeof Point);//function,說明類的數據類型本身就是函數,類本身指向構造函數
var a = new Point(1,2);//只有x,y,并沒有constructor,__proto__中有constructor,說明類的所有方法和屬性都定義在了類的prototype屬性上面
console.log(a)//1,2
console.log(a.toString())//3,在類的實例上調用方法,實際上是在調用原型上的方法
//類和模塊的內部,默認就是嚴格模式,所以不需要使用use strict指定運行模式。只要你的代碼寫在類或模塊之中,就只有嚴格模式可用。
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function
//類相當于實例的原型,所有在類中定義的方法,都會被實例繼承。如果在一個方法前,加上static關鍵字,就表示該方法不會被實例繼承,而是直接通過類來調用,這就稱為“靜態方法”。
class Foo {
static bar () {
this.baz();
}
static baz () {
console.log('hello');
}
baz () {
console.log('world');
}
}
Foo.bar() // hello
//如果靜態方法包含this關鍵字,這個this指的是類,而不是實例。
//上面代碼中,靜態方法bar調用了this.baz,這里的this指的是Foo類,而不是Foo的實例,等同于調用Foo.baz。另外,從這個例子還可以看出,靜態方法可以與非靜態方法重名。
class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();//子類B的構造函數之中的super(),代表調用父類的構造函數
}
}
//super雖然代表了父類A的構造函數,但是返回的是子類B的實例,即super內部的this指的是B
new A() // A
new B() // B
轉載于:https://www.cnblogs.com/kaw19950302/p/7834088.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的ES6——class的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 买二手房办证件需要卡里有钱吗
- 下一篇: 标准C程序设计七---53