Javascript prototype

I'm trying to understand js prototype property: my code example

function Container(param) {
    this.member = param;
}

var newc = new Container('abc');


Container.prototype.stamp = function (string) {
    return this.member + string;
}

document.write(newc.stamp('def'));

function Box() {
    this.color = "red";
    this.member = "why";
}

Container.prototype = new Box();
Box.prototype.test = "whatever";
var b = new Box();

document.write(newc.test);

here the last line is undefined - although the Container prototype is a Box and Box prototype, it has a property test, why does newc, which refers to the test in Box, not work? can someone explain how 'Prototype' works in my context above.

Thank...

+4
source share
3 answers

You install the prototype Containerin Box()after the instance newchas already been created.

Change the order of the statements as follows:

function Container(param) {
    this.member = param;
}

function Box() {
    this.color = "red";
    this.member = "why";
}

Container.prototype = new Box();
Box.prototype.test = "whatever";
Container.prototype.stamp = function (string) {
    return this.member + string;
}

//Here the containers prototype setup is complete.
var newc = new Container('abc');

document.write(newc.stamp('def'));

document.write(newc.test);
+2
source

, , , , "" . .

, "", , . :

function Container(param) {
    this.member = param;
}

var newc = new Container('abc');

// setting a new property of the prototype, after newc instantiated.
Container.prototype.stamp = function (string) {
    return this.member + string;
}

// This already-instantiated object can access the stamp function
document.write(newc.stamp('123')); // output: abc123

, , . . :

// Our Box object
function Box() {
    this.color = "red";
    this.member = "why";
}

Container.prototype = new Box();
var newd = new Container('fgh');
document.write(newd.stamp('456')); // output: ERROR

! , ? "" "Box", "".

, , "Box" "Container". . , :

// Our Box object
function Box() {
    this.color = "red";
    this.member = "why";
}

// This inherits from Container. Note that we can
//   do this before or after we declare "Box"
Box.prototype = new Container();

Box.prototype.test = "Whatever";
var b = new Box("jkl"); // note: "jkl" is ignored because "Box" sets "member" to "why"

document.write(b.test); // output: Whatever
document.write("<br>");
document.write(b.stamp("345")); // output: why345

, "", , "".

, , - , , , , . , - .

+2

, . , , .

, .

4.2.1:

, , ( ) "prototype". , ..; . , , . , , , ; , , ; , ; ..

0

All Articles