Misunderstanding i have about javascript prototype inheritance

Simple questions.

    function p()
    {
        function A()
        {
            this.random = "random";
        }
        A.prototype.newfunc = function(){ alert("5");}

        function B()
        {

        }

        B.prototype = new A();

        var bObj = new B();
    }

Q1: When I install prototype B, I do not understand how the property of prototype B will be updated when the prototype A / if is updated. I mean, it just inherits / copies all of these properties. This is not true:

B.prototype = A.prototype

where B and A are one.

Q2: After A is returned and initialized to the prototype object B, how does JS not know to enable this prototype property? I mean, we never faced this situation, because the JS interpreter knows how to simply chop off the property of prototype A:

B.prototype = new A(); //any A object has an associated prototype object
    B.prototype.prototype;//after initialization we no longer have the separate prototype property of A
+3
source share
2 answers

Q1: - . , B A. A, B . , , A B, - , . B.prototype , A.

:

    function A()
    {
    }

    A.prototype.alertname = function () 
    {
        alert (this.name);
    };

    function B()
    {
    }

    B.prototype = new A();

    var bObj = new B();
    var aObj = new A();

    A.prototype.name = "A"; 
    aObj.alertname(); // output is "A";
    bObj.alertname(); // output is "A";

    B.prototype.name = "B";
    aObj.alertname(); // output is "A";
    bObj.alertname(); // output is "B";

Q2: , . B.prototype, A , "" B. , , A, B, A. , "" . :

function iterateMembers ( obj ) {
    var str = "";
    for (var member in obj) {
        str += member + ", "
    }
    alert (str);
}

iterateMembers (aObj);
iterateMembers (A.prototype); 

, aObj, A.prototype "prototype".

iterateMembers (A);
alert (typeof(A));

, , A, B ( ), "prototype".

+2

Q1: B, , B A/if. , / .

prototype:

function A(name) { this.name = name }

print(A.prototype) // [object Object]

new A, constructor, :

var a = new A('Eric')

print(a.constructor == A) // True
print(a.constructor.prototype == A.prototype) // True

a, undefined, JavaScript a (, a.constructor.prototype). , a:

A.prototype.greet = function() { print('Hi, ' + this.name + '!') }

a.greet() // Hi, Eric!

.

function B(name) { this.name = name.toUpperCase() }
B.prototype = new A
b = new B("Eric")
b.greet() // Hi, ERIC!

, , JavaScript "" b, b. , * b , .

, A: B.prototype.prototype

, . :

B.prototype.constructor.prototype
+1

Source: https://habr.com/ru/post/1781590/


All Articles