构造函数如果采用以下这种方式声明,并不能为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