W
W
Winner7772014-04-06 01:04:21
JavaScript
Winner777, 2014-04-06 01:04:21

What is prototype in javascript?

The question is probably overused and despite the number of abstruse descriptions available on the Internet, I still do not understand what it is. Therefore, I ask you to explain with a specific example:
jsfiddle.net/Winner/LjG8n
The task is as follows: register an event for filling out the form inside my class so that inside the event I can call the method of an object of this class, that is, the method should not be static. Right now when I click on submit I have undefined when I try to output the x attribute.
jsfiddle.net/Winner/LjG8n/2
In the same example, something more decent is displayed as the value of X, but the same for two objects.
Actually why and how should I be in my situation?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Pushkarev, 2014-04-06
@Winner777

jsfiddle.net/ck89g/1
Prototype (Constructor.prototype) - an object that is cloned by reference when creating a constructor instance via new. An object is created with a hidden property, in some engines the property is available as Instance.__proto__. When getting instance properties, if they are not present in the new object, the engine looks for them in the prototype. New properties are written to the instance without changing the prototype.
In the example, you also have problems understanding the context of the call (this) of the function. In the constructor (when called via new), this will be a new object created from the prototype. In a method, this is the object from which it is called (up to the last dot). When called as a function (without dots), it is a global object (window). The context can be bound by the .bind function method or run the function in an arbitrary context - .call, .apply.
You are adding a method and a property to the prototype every time the constructor is called, and you are running the method in the context of the prototype, not the instance.

L
lega, 2014-04-06
@lega

What is prototype in javascript?

In simple terms, this is the ability to use the object (function / variable) of the "parent" (prototype) if there is no object of its own.
For example, you are trying to call the form1.echoX() function, because it is not there, there will be an attempt to call form1.__proto__.echoX(), if this is not present, then form1.__proto__.__proto__.echoX(), etc.
How to "populate" the prototype can be found in "any" JS tutorial, also @rock gave an example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question