2
考慮下面DOM上下文如何保持在角DOM
<div ng-controller="A">
<button ng-click="sayHello()">SayHello</button>
</div>
<div ng-controller="B">
<button ng-click="sayHello()">SayHello</button>
</div>
A(){
var sayHello() = function(){
console.log("Hello")
}
}
B(){
var sayHello() = function(){
console.log("Hello")
}
}
假設我們有2控制器A和B他們每個人都有sayHello()
方法。
- 函數的上下文是如何維護的?
- 角怎麼知道要調用哪個函數?
- 如何用原生JavaScript實現相同?
編輯1 - 如何上下文DOM關聯
<script>
var module = {
namspace: {}
}
var module.namspace.object1 = {}
var module.namspace.object1.someFunction = function(){}
var module.namspace.object2 = {}
var module.namspace.object2.someFunction = function(){}
</script>
<div context="module.namspace">
<div context="object1">
<button id="button1" onClick="someFunction()">Click Me</button>
</div>
<div context="object2">
<button id="button2" onClick="someFunction()">Click Me</button>
</div>
</div>
所以,預期的行爲是:
- 當我點擊
#button1
module.namspace.object1.someFunction
需要得到所謂 - 時我點擊
#button2
module.namspace.object2.someFunction
需要撥打