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

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>');

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)

Not the answer you're looking for? Browse other questions tagged or ask your own question.