为什么不能重写该类的原型?

时间:2019-05-14 15:08:38

标签: javascript

我们可以重写该函数的原型,但不能重写该类的原型吗?

true

1 个答案:

答案 0 :(得分:1)

这是因为您实际上并未设置B.prototype的值。 You can't set Object.prototype。对于Function.prototype,没有什么可以阻止您覆盖该值。请注意,我如何将Function.prototype更改为字符串,而我不能更改该类。

function A() {
}

class B {
}

let _APrototype   = A.prototype;
let _BPrototype = B.prototype;
console.log(A.prototype);
console.log(B.prototype);

A.prototype = "test A";
B.prototype = "test B";
console.log(A.prototype); // Should have been set.
console.log(B.prototype); // Did not actually set.
    
A.prototype = function () {
};
B.prototype = function () {
};

console.log(A.prototype); // Should have been set.
console.log(B.prototype); // Did not actually set.
    
console.log(_APrototype == A.prototype); //false
console.log(_BPrototype == B.prototype); //true

请注意,您仍然可以将函数添加到类的原型中。您只是无法更改。这可能是由于持有该类的基础对象函数。如果覆盖此参数,则将丢失所有继承的基础对象函数。

class B {
}

console.log(B.prototype.someMethod1); // Shouldn't exist.
console.log(B.prototype.someMethod2); // Shouldn't exist.
console.log(B.prototype.hasOwnProperty); // Inherited.

B.prototype.someMethod1 = function someMethod1() {
};
console.log(B.prototype.someMethod1); // Should now exist.
console.log(B.prototype.someMethod2); // Still doesn't exist.
console.log(B.prototype.hasOwnProperty); // Inherited.

// This can work depending on which JS features are supported.
B.prototype = {
  someMethod2: function() {
    
  }
}

console.log(B.prototype.someMethod1); // Should be removed now.
console.log(B.prototype.someMethod2); // Should now exist.
console.log(B.prototype.hasOwnProperty); // Inherited even though we completely overwrote the previous set of methods.