1

As you know, in javascript functions are objects, my problem is with the following code:

function Car() {
 this.color = "black";
}
console.log(Car.name);
console.log(Car.color);

Output: Car undefined

Since I could access name property of Car object why can't I access color property of Car object in the same way.

Another example:

console.log("Hello".charAt.name);
console.log("Hello".charAt.length);  

Output : charAt 1

Here charAt is a method of String object but I used its name as a reference to access name and length properties and not only these properties but also some methods such as : hasOwnProperty and isPrototypeOf

My question is what exactly those properties and methods?

3
  • 3
    Because color is set at the construction time to the object of the type Car and is not a property of the type itself. ( carObj = new Car(); console.log(carObj.color); ) Commented Nov 5, 2015 at 14:32
  • How do you expect to access stuff inside the function if you don't even execute the function? The line this.color = "black"; is never ever execute. If you do a console.dir(Car) you can see which properties function have. Commented Nov 5, 2015 at 14:35
  • 2
    Read the docs! developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Nov 5, 2015 at 14:37

2 Answers 2

2

In class terms, name is a property of the class Car whereas color is a property of an instance of the class Car. You can only access the color property when you create a new instance of it.

function Car() {
  this.color = "black"; 
}
var car = new Car()
document.write(Car.name +'<br>');
document.write(car.color +'<br>');

Sign up to request clarification or add additional context in comments.

Comments

0

in your first example you're trying to access the property color of function Car;

function Car() {
 this.color = "black";
console.log(this)//Window {}
};

/*you need to set Car.color */
Car.color = 'white';
console.log(Car.name);//Car
console.log(Car.color);//white

Car();

console.log(color)//black


//Car
//white
//Window {}
//black

while name property is set automatically in function declarations..

when called normally, in a non strict situation, this inside the function refers to Window object ( which is global on browser );


on the other hand if you call the function as a constructor this refers to return object:

function Car() {
 this.color = "black";
console.log(this)   //object instance assigned to mazda
};
 var mazda = new Car();
console.log(mazda.color)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.