简体   繁体   中英

What is Prototype COMPOSITION or INHERITANCE?

Is the purpose of prototype to create methods and properties globally? So that means all the instance can access it? The said methods and properties are not inside the constructor, is that means they are not created every time an object is created?

Is prototype an object inside TheClass?

TheClass.prototype.someProperty = "hello";

So in the statement above, is that creating property inside the prototype object? If so then how can a class access that property if it is created inside the prototype object?

these is how to access the property

var obj = new TheClass();
alert(obj.someProperty);

not this

alert(obj.prototype.someProperty);

also toString() is inside the prototype object you called the toString() by calling the object the toString belongs, but toString() belongs to prototype object right?

How come it is called by calling the object not the prototype who is inside an object. im familiar with java this is called COMPOSITION .

so why this work? I understand if its INHERITANCE but no it is COMPOSITION and we didnt write a statement delegating the toString() method of prototype to the object.

alert(theClass);

not

alert(prototype);

Classes which inherit from a particular class have access to the methods on that class's prototype. That makes prototype an inheritance-based construct.

Is the purpose of prototype to create methods and properties globally?

Yes. Prototype allows you to give instances of a class methods and properties which can be inherited from that class.

So that means all the instance can access it?

Yep.

Is prototype an object inside TheClass?

No. Prototype is a set of properties which classes inheriting from TheClass are granted access to as well. If a property isn't found on a particular object it will search the prototype chain for that property.

Properties in JS are looked up using the prototype chain

https://developer.mozilla.org/en/JavaScript/Guide/Inheritance_constructor_prototype

Is the purpose of prototype to create methods and properties globally?

Yes, you add properties and methods to the prototype such that all instances of the function have access to the same methods and properties. Any changes to methods/properties in a function's prototype affect all instances of that function

So that means all the instance can access it?

Yes.

The said methods and properties are not inside the constructor, is that means they are not created every time an object is created?

Yes, they aren't re-created on every initializaiton - that is one of the main purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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