简体   繁体   English

从子对象调用父母构造函数和原型

[英]Call parents constructor and prototype from child object

I am trying to understand the methods to call constructor and prototype methods in JavaScript. 我试图理解在JavaScript中调用构造函数和原型方法的方法。

Here is my try: 这是我的尝试:

function A() {
    this.getId = function() {
        console.log('A constructor - getId');
    }
}
A.prototype.getId = function() {
    console.log('A prototype - getId');
}
function B() {
    A.call(this);
    this.getId = function() {
        console.log('B constructor - getId');
    }
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

B.prototype.getId = function() {
    console.log('B prototype - getId');
}
var p = new A();
var q = new B();

p.getId()
//A constructor - getId 

q.getId()
//B constructor - getId

p.constructor.prototype.getId()
//A prototype - getId 

q.constructor.prototype.getId()
//B prototype - getId  

Are last two ways are correct way to Call prototype methods? 最后两种方法是调用原型方法的正确方法吗?

How can I call parents constructor and prototype methods from child object q? 如何从子对象q调用父级构造函数和原型方法?

So, how can I get 所以,我怎么得到

'B prototype - getId' from q object 来自q对象的'B prototype-getId'

Because q is an instance of B . 因为qB的实例。 The B constructor assigns a getId method directly on the instance, so that's the one you get. B构造函数直接在实例上分配getId方法,这就是您所获得的方法。 If you were expecting the one on B.prototype , then you need to remove (or not assign) the one on the instance: 如果您期望在B.prototype上使用一个,则需要删除(或不分配)该实例上的一个:

// delete getId on instance
delete q.getId; 

// Now get inherited getId
q.getId()  // B prototype - getId

Note that the delete operator only works on own properties, it won't delete properties on the [[Prototype]] chain. 请注意, delete运算符仅对自己的属性起作用,而不会删除[[Prototype]]链上的属性。

Are last two ways are correct way to 最后两种方法是正确的方法吗

  1. Call parents prototype method using p Parents constructor method using 使用p调用父母原型方法使用
  2. q q

"Correct" in that they work, though I wouldn't design it to work that way. “正确”的意思是它们可以工作,尽管我不会设计这种方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM