我希望有人能解釋這種行爲,因爲我覺得它很讓人煩惱。我有一個OnMissingMethod實現父類從外部文件中成功地提供隱含的getter/setter方法(舊CF8應用程序)必須在擴展類中使用OnMissingMethod的'this'作用域
如果我實例子類爲富並調用foo.getBar(),它觸發OnMissingMethod,但如果在foo類本身中,我會調用getBar()它不會。它會觸發OnMissingMethod的唯一方法是如果我使用this.getBar(),我不喜歡審美和代碼不一致的原因。
tldr;這裏是一個代碼示例...自己嘗試一下。
Foo.cfc
<cfcomponent output="false" extends="Parent">
<cffunction name="init" output="false" returntype="Foo">
<cfreturn this />
</cffunction>
<cffunction name="getInternalBar_workie">
<cfreturn this.getBar() />
</cffunction>
<cffunction name="getInternalBar_noworkie">
<cfreturn getBar() />
</cffunction>
</cfcomponent>
Parent.cfc
<cfcomponent output="false">
<cffunction name="OnMissingMethod">
<!--- always return true for this example --->
<cfreturn true />
</cffunction>
</cfcomponent>
foobar.cfm
<cfset foo = CreateObject("component", "Foo").init() />
<!--- this works --->
<cfdump var="#foo.getBar()#" /><br/>
<!--- this works --->
<cfdump var="#foo.getInternalBar_workie()#" /><br/>
<!--- this fails --->
<cfdump var="#foo.getInternalBar_noworkie()#" />
誰能解釋爲什麼OnMissingMethod在從類本身調用時必須使用'this'範圍?有更好的解決方法嗎?
在回顧Adam的回答後,它看起來像被卡住了。通過以這種方式調用不存在的方法,您嘗試解決的實際問題是什麼? – imthepitts
我有大量的服務(+/- 1000),都與其他服務有依賴關係。我正在使用ColdSpring來管理DI,並使用屬性注入來注入服務。這當然要求目標服務內部的注入服務有一個可用的getter。我沒有明確寫出成千上萬的鍋爐板getter方法,而是做了同樣的事情,我讓所有的服務都擴展了一個BaseService,並且在那個類中有一個OnMissingMethod,它查找getFooService()和setFooService(fooService)模式並且做。 .. –
...適當的設置工作將它們放置在目標中的變量[「_ dependencies」]集合中。缺點是,雖然設置正常工作,但任何時候我想引用注入的服務,我需要做的是:variables [「_ dependencies」]。fooService或this.getFooService()。我使用this.getFooService()時遇到的問題是,它與我在同一個類中調用其他方法的方式不一致。這當然不是關鍵問題,但這並不意味着我喜歡它。 –