Here's my javascript object, I would like to know how to avoid using "this" so many times in prototype. I know there is lot of theory and links for prototypal inhericance and this has probably been answered already, but as I haven't been able to make all ends meet, I thought this may be worth another question.
function shape(smth) {
this.a = smth
this.b = 2
this.c = 3
}
shape.prototype.doCalculus = function () {
return this.a * this.b + this.c - (2 * (this.b + this.c) + this.a);
}
module.exports = shape
__proto__ is a way to inherit properties from an object in JavaScript. __proto__ a property of Object. prototype is an accessor property that exposes the [[Prototype]] of the object through which it is accessed. POSTly is a web-based API tool that allows for fast testing of your APIs (REST, GraphQL).
As others have said the first version, using "this" results in every instance of the class A having its own independent copy of function method "x". Whereas using "prototype" will mean that each instance of class A will use the same copy of method "x".
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
The prototype property is set to function when it is declared. All the functions have a prototype property. proto property that is set to an object when it is created using a new keyword. All objects behavior newly created have proto properties.
If you want public members of an object, they MUST be referenced from the this
pointer. That's how OO works in Javascript. No alternative.
If you have lots of references to the same variable within a function, you can temporarily put it in a local variable just to save some reference logic (same as with any multiple step reference), but you will still have to initially retrieve using this.varName
.
There is a scheme that uses "private" member variables in a constructor closure and does not use the prototype that can be used in some situations and this allows you to refer to the variables directly without this use of this
:
function shape(smth) {
var a = smth,
b = 2,
c = 3;
this.doCalculus = function() {
return a * b + c - (2 * (b + c) + a);
}
}
module.exports = shape
For object types where you create lots of instances, this may consume a bit more memory because methods are not stored on a shared prototype, but are created separately for each instance. There are those who argue the difference in memory consumption is immaterial in most uses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With