简体   繁体   English

在对象属性由另一个函数分配后访问

[英]Access object properties after they are assigned by another function

I'm new to Javascript, and I'm learning how to use OOP principals. 我是Java语言的新手,并且正在学习如何使用OOP主体。 I'm stuck on assigning object properties and then accessing them later. 我被困在分配对象属性,然后再访问它们。 Let's say I have this function that assigns properties to an object "Car". 假设我有此函数,可将属性分配给对象“ Car”。

function assignProps()
{
Car.size="small";
Car.cost="expensive";
}

The object Car with empty properties because they are assigned from the function. 具有空属性的对象Car,因为它们是从函数分配的。

var Car =
{
size:"",
cost:"",
returnSize: function()
            {
           return this.size;
            },
returnCost: function()
            {
           return this.cost;
            },

}

Now, I want to call the function that assigned the value, and then access Car's properties. 现在,我想调用分配值的函数,然后访问Car的属性。 I tried doing this, but it obviously failed: 我尝试这样做,但显然失败了:

function accessProps()
{

assignProps();
console.log(Car.returnSize());
console.log(Car.returnCost());

}

Any help would be appreciated. 任何帮助,将不胜感激。 I have a feeling that this might have to do with constructors or prototypes, but since there are so many ways to create custom objects in Javascript, the documentations are very confusing. 我感觉这可能与构造函数或原型有关,但是由于有许多方法可以在Javascript中创建自定义对象,因此文档非常混乱。

EDIT: By "fail" I mean that it outputs the blank instead of the newly assigned value EDIT: I tried doing it this way as well, and it yielded the same result. 编辑:“失败”是指它输出空白而不是新分配的值。编辑:我也尝试过这种方式,并且产生了相同的结果。

You have some errors in your code: 您的代码中有一些错误:

var Car = {
   size:"",
   cost:""
}

And if you look at this fiddle: http://jsfiddle.net/JskBy/ It works as expected. 如果您看这个小提琴: http : //jsfiddle.net/JskBy/它将按预期工作。

Full code: 完整代码:

function assignProps() {
    Car.size="small";
    Car.cost="expensive";
}

var Car ={
    size:"",
    cost:""
}
function accessProps(){
  assignProps();
  console.log(Car.size);
}

assignProps();
accessProps();

汽车对象初始化时出现语法错误,应为

var Car = { size: "", cost: "" };

Line 18, column 14: Extra comma. 第18行,第14列:逗号。

Line 20, column 2: Missing semicolon. 第20行,第2栏:缺少分号。

Try to get a developing tool with JSLint/JSHint built-in (eg Notepad++ with add-on), it might help you with debugging problems like this. 尝试获得带有内置JSLint / JSHint的开发工具(例如,带有附加组件的Notepad ++),它可能会帮助您解决此类调试问题。

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

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