当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Implementing a function to access an object's property versus accessing the property using dot notation, or bracket notation?

问题描述:

Reviewing some 3rd party code, I have found a function written to get a property of an object.

function getObjectProperty (obj, propertyName) {

var o;

if (obj) {

o = obj[propertyName];

if (o != null) {

if (typeof o == 'function') return o();

}

}

return o;

}

An example how this function is called is:

var foo = getObjectProperty(r, 'objProp')

Is there some benefit to using this custom function to fetch the property, rather than just doing this:

var foo = r.objProp

or

var foo = r['objProp']

I just don't understand the benefit of using this function, if there is one? I could not find another example of this function, so I can only assume that it was custom made for this application. The only thing I can see is that it returns a function call if the object property is a function, but even then you could just write:

var foo = r.objProp()

网友答案:

Simple difference. If given an object like:

var foo = { a: "a", b: function() { return "b" } }

Then foo.b or foo[b] gives a different result to getObjectProperty(foo,"b")

It appears to be a utility function to get a property and if it's a "getter" function, automatically call it. Getters are fairly recent and many older browsers don't support them (IE didn't get them until 9 I believe).

Of course, if the function assigned to b returned a function instead of a value, then it wouldn't unwrap, but presumably that wasn't the intention.

So why might this be useful? Because getters are useful. Imagine you had an object like this:

function order(quantity, price) {
    this.quantity = quantity;
    this.unitPrice = price;
    this.totalPrice = function() { return this.quantity * this.unitPrice }
};

var myOrder = new order(10,2);

If I want to look at the properties of myOrder then I need to know as a consumer of this object that totalPrice is a function. If I use getObjectProperty instead, then I don't need to care about it. It will do the right thing and I don't need to worry about how it calculated totalPrice

网友答案:

This looks like a (terribly named) utility function that, as you realized yourself, tries to get the value of the property from the object, but if that is a function, return the result of calling it.

网友答案:

Isn't it obvious from the code?

This line invokes if the property is a function:

   if (typeof o == 'function') return o();

Although it doesn't get the property and the function doesn't do what it is supposed to. getObjectPropertyButIfFunctionInvokeInstead() more suitable name.

It is poorly written code

分享给朋友:
您可能感兴趣的文章:
随机阅读: