JS中的属性与方法的示例 [英] Example of Properties vs. Methods in JS
问题描述
我对属性和方法之间的语义区别进行了很好的描述(通过 http://www.webdeveloper.com/forum/showthread.php?133712-Properties-Vs.-Methods ):
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.-Methods):
属性就像名词.它们具有值或状态.
Properties are like nouns. They have a value or state.
方法就像动词.他们执行动作.
Methods are like verbs. They perform actions.
属性无法执行操作,方法具有的唯一值是完成操作后返回的值.
A property can't perform an action and the only value that a method has is the one that is returned after it finishes performing the action.
例如
属性:门; 可能的值:打开,关闭
Property: door; Possible Values: open, closed
方法:openDoor; 操作:将door属性的值更改为打开"
Method: openDoor; Action: to change the value of the door property to "open"
创建示例:我从理论上理解了这一点,但我无法提出一个示例.是否可以向我展示door/openDoor在实际的Javascript代码中的外观?
Creating an example: I understand this in theory but I can't come up with an example. Would it be possible to show me how the door/openDoor would look in actual Javascript code?
推荐答案
确实,您需要备份并阅读上面发布的一些链接.但举个简单的例子:
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 ;
}
此处house
是对象.它具有属性:house.isDoorOpen
.在这里,它更像一个形容词.门是打开的(true)还是关闭的(false).听起来,它描述了房屋的属性.
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.
此外,它还具有方法openDoor
(其用法如下:house.openDoor()
).那是它可以做的.在这种情况下,操作openDoor
会影响isDoorOpen
属性,使其变为true.
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.
这篇关于JS中的属性与方法的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!