2

I am reading Javascript for Kids by Nick Morgan as a beginner, and I produced the following JavaScript code -

var Car = function(x,y) {
    this.x = x;
    this.y = y;
}

Car.prototype.draw = function () {
    var carHtml = '<img src="http://nostarch.com/images/car.png">';
    this.carElement = $(carHtml);

    this.carElement.css({
        position:"absolute",
        left:this.x,
        top:this.y
    });
}

var tesla = new Car (20,20);
var nissan = new Car (100,200);

tesla.draw();
nissan.draw();

Now, I used the JavaScript constructor method to create objects and prototypes technique to create the draw method, which I can call on the car objects I have created from each instance of car.

From my experience in Python, all methods can access all the properties of an object created from an instance of a class.

My question is, are properties accessible by all methods in an object created by the car constructor?

Satpal
  • 132,252
  • 13
  • 159
  • 168
Dave Smith
  • 185
  • 1
  • 2
  • 9
  • 1
    __Yes__, they are. – Satpal Jul 28 '17 at 11:21
  • Note that your `Car` constructor doesn't create any methods at all. The code adding `draw` to `Car.prototype` creates the only "method" (this is "method" in the loose sense; as of ES2015, JavaScript got a stricter form of methods). – T.J. Crowder Jul 28 '17 at 11:30

2 Answers2

2

My question is, are properties accessible by all methods in an object created by the car constructor?

They're accessible to any code that has access to the object. So if a method created by the Car constructor (or anything else) has access to the object, then yes, the properties will be accessible to it. If the method created by the Car constructor doesn't (e.g., it's creating a method on a different object entirely), then that method may not have access to the properties.

Note that whether the method has access to the object may vary depending on how it's called, if it's accessing the object via this. More: How to access the correct this inside a callback?

JavaScript has no truly private properties, yet. If you can access the object, you can access all of its true properties.

There is a proposal, currently at Stage 3*, to add private fields to JavaScript objects created via class syntax. (It used to be a separate private properties proposal, but it was combined with that class fields proposal.) Private data has had a long an tortured path to date, and while the proposal has reached Stage 3, it still has a fair bit of road to travel.


* Explanation of stages

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Properties like what you defined are a public properties (no such a thing protected in js) and as such are accessible from any other scope having the instance of the object , the real private properties (created with "var" keyword) are only accessible within their closure (meaning: their defined function block or nested blocks).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875