1. 程式人生 > 其它 >ES6——class 基本語法

ES6——class 基本語法

建構函式如果採用以下這種方式宣告,並不能為Point類生成一個名name為‘y1’的屬性property。

Object.assign(Point.prototype, {
  constructor(x,y){
         this.x=x;
         this.y1=y;
     },
  fun1(){}
});

完整demo如下:macOs+chrome(啟動devtools除錯,option+command+i)

// let methodName = 'getSum'

class Point{
     constructor(x,y){
         this
.x=x; this.y=y; } add(a, b){ return a+b; } get(){ return this.x+this.y; } get1(){ return this.y1+this.y } } Object.assign(Point.prototype, { constructor(x,y){ this.x=x; this.y1=y; }, fun1(){} }); Point.prototype.fun2
= function(){} var p = new Point(1,2); console.log(Object.keys(Point.prototype)) console.log(Object.getOwnPropertyNames(Point.prototype)) console.log(Object.getOwnPropertyNames(p)) console.log(Object.getOwnPropertyNames(new Point(3,4))) console.log(p.hasOwnProperty("x")) console.log(p.hasOwnProperty(
"y")) console.log(p.hasOwnProperty("y1")) console.log(p.get()) console.log(p.get1())

結果:

(2)['fun1', 'fun2']
(6)['constructor', 'add', 'get', 'get1', 'fun1', 'fun2']
(2)['x', 'y']
(2)['x', 'y']
true
true
false
3
NaN
undefined