Example of Properties vs. Methods in JS

前端 未结 2 1530
醉话见心
醉话见心 2020-12-08 05:44

I found a great description of the semantic difference between Properties and Methods (paraphrased, via http://www.webdeveloper.com/forum/showthread.php?133712-Properties-Vs

相关标签:
2条回答
  • 2020-12-08 06:17

    Really, you need to back up and read some of the links posted above. But as a quick example:

    var house = {} ;
    
    house.isDoorOpen = false ;
    
    house.openDoor = function(){
        house.isDoorOpen = true ;
    }
    

    Here house is the object. It has a property: house.isDoorOpen. Here, it is more like an adjective. Either the door is open (true) or closed (false). As it sounds, it describes a property of the house.

    Also, it has a method openDoor (which is used like this: house.openDoor() ). That's something that it can do. In this case, the action openDoor affects the isDoorOpen property, making it true.

    0 讨论(0)
  • 2020-12-08 06:33

    Let's look at how the javascript spec ECMA-262 describes the term property

    http://www.ecma-international.org/ecma-262/5.1/#sec-4.3.26

    4.3.26 property

    association between a name and a value that is a part of an object

    NOTE Depending upon the form of the property the value may be represented either directly as a data value (a primitive value, an object, or a function object) or indirectly by a pair of accessor functions.

    4.3.27 method

    function that is the value of a property

    NOTE When a function is called as a method of an object, the object is passed to the function as its this value.

    Also

    Javascript's definition of attribute is different from Java's

    4.3.29 attribute

    internal value that defines some characteristic of a property


    for in, loops through an object's enumerable properties, and that includes its functions

    http://eloquentjavascript.net/1st_edition/chapter8.html

    "A function is called as a method when it is looked up as a property, and immediately called, as in object.method()."

    There does seem to be a more standard definition of property..

    https://en.wikipedia.org/wiki/Property_(programming)#JavaScript

    "A property, in some object-oriented programming languages, is a special sort of class member, intermediate between a field (or data member) and a method. .... Some object-oriented languages, such as Java, don't support properties, and require the programmer to define a pair of accessor and mutator methods instead."

    In that more standard, non-javascript definition of property

    C# has properties, and Java doesn't have properties

    0 讨论(0)
提交回复
热议问题