1. 程式人生 > 其它 >開發中方法與函式的區別

開發中方法與函式的區別

技術標籤:javascript

  1. 方法(method)
    在類裡的一般稱之為方法,因為方法都是和某個例項物件掛鉤的
    例子:
const obj = {
	counter = 0,
	msg :'hello'
}
const app = new Vue({
	el:'#app',
	data: obj,
	methods:{
		add: function(){
			this.counter++
		},
		sub: function(){
			this.counter--
		}
	}
})

在此程式碼塊中,add和sub都被稱為方法,因為裡面的this和例項化物件app相掛鉤。

  1. 函式(function)
    如果在script中直接定義,則被稱為函式
    例子:
<script>
	function f(){
		counter++;
	}
</script>
  1. js中既有方法又有函式,java中只有方法的概念