简体   繁体   English

JavaScript:默认对象的属性和方法

[英]JavaScript: default object's properties and methods

As you know, in javascript functions are objects, my problem is with the following code: 如您所知,在javascript函数中是对象,我的问题是以下代码:

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. 由于我可以访问Car对象的name属性,所以为什么不能以相同的方式访问Car对象的color属性。

Another example: 另一个例子:

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

Output : charAt 1 输出 :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 这里的charAt是String对象的方法,但我使用其名称作为访问名称长度属性的引用,不仅访问这些属性,还访问了诸如hasOwnPropertyisPrototypeOf之类的一些方法。

My question is what exactly those properties and methods? 我的问题是那些属性和方法到底是什么?

In class terms, name is a property of the class Car whereas color is a property of an instance of the class Car . 在类的术语, name是类的属性Car ,而color是一个类的实例的属性Car You can only access the color property when you create a new instance of it. 您只能在创建其新实例时访问color属性。

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

in your first example you're trying to access the property color of function Car ; 在第一个示例中,您尝试访问function Car的属性color

 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.. 而name属性是在函数声明中自动设置的。

when called normally, in a non strict situation, this inside the function refers to Window object ( which is global on browser ); 当在非严格情况下正常调用时, this函数内部将引用Window对象(在浏览器上是全局对象);


on the other hand if you call the function as a constructor this refers to return object: 另一方面,如果您将该函数作为构造函数调用,则this是指返回对象:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM