某些方法如何在原型中,但不能通过Object.assign传递,而另一些方法是

问题描述 投票:0回答:1

采用以下A,B和C类及其实例a,b和c

class A {
    constructor() {
        this.method1 = function() {}
    }

    method2() {}
}

A.prototype.method3 = function() {};


class B extends A {
    constructor() {
        super();
    }
}


class C {
    constructor() {}
}

Object.assign(C.prototype, A.prototype);

const a = new A();
const b = new B();
const c = new C();

B类为什么继承了方法2但C类却没有?

以下陈述如何都成立?

A.prototype.method2 !== undefined
c.method2 === undefined

[如果您想知道c.method3 !== undefined,那么我无法理解两者之间存在一些根本性的区别。

您可以在这里https://jsfiddle.net/pdn64bv2/随意摆弄

javascript class inheritance prototype
1个回答
1
投票

有两件事合谋产生这种效果:

1] Object.assign将仅复制对象的enumerable own properties。任何不可枚举的属性都不会被复制

2]当使用class关键字时,定义的任何方法都是not不可枚举的。这与使用A.prototype.method3 = function() {}向对象分配某些内容时不同,在该对象中,属性[[will是可枚举的。

因此,由于A.prototype.method2不可枚举,因此当您执行Object.assign(C.prototype, A.prototype);时,它不会被放入C.prototype。>

查看类方法不可枚举的另一种方法是使用Object.keys。用class关键字定义的内容不存在:

class A { constructor() { this.method1 = function() {} } method2() {} } A.prototype.method3 = function() {}; console.log(Object.keys(A.prototype)); console.log(A.prototype.method2); // it's there console.log(Object.prototype.propertyIsEnumerable('method2')); // but it's not enumerable

0
投票

有两件事合谋产生这种效果:

1] Object.assign将仅复制对象的enumerable own properties。任何不可枚举的属性都不会被复制

2)class关键字使您使用它定义的任何方法都无法枚举。

查看它们不可枚举的另一种方法是使用Object.keys。用class关键字定义的内容不存在:

class A {
    constructor() {
        this.method1 = function() {}
    }

    method2() {}
}

A.prototype.method3 = function() {};

console.log(Object.keys(A.prototype));
© www.soinside.com 2019 - 2024. All rights reserved.