2011-03-24 71 views
2

的,我想我可能會在谷歌搜索會失敗,也許這種模式只是不使用JavaScript處理MRO的方式放進去,但我在尋找一個相當於Perl的AUTOLOAD方法使得:的JavaScript相當於Perl的AUTOLOAD

function car() { 
    return { 
    start: function() { alert('vrooom') }, 
    catchall: function() { alert('car does not do that'); } 
    } 
}; 

car().start(); //vrooom 
car().growBeard(); //car does not do that 
在Perl

迅速處理這種情況我會寫:

sub AUTOLOAD { __PACKAGE__." doesn't do that" } 

但語法趕上一個未定義的方法在JavaScript中我摸不透。 也許重載.call或.apply什麼的?

回答

2

如果你只是想知道,如果定義一個方法,你可以做到以下幾點:

if(car().growBeard){ 
} 


這聽起來像你正在尋找的是__noSuchMethod__但它僅在Mozilla支持,而不是正式ECMAScript規範的一部分。

function car() { 
    return { 
    start: function() { alert('vrooom'); }, 
    __noSuchMethod__ : function(){alert('no method');} 
    }; 
} 

__noSuchMethod__jsfiddle實施例,只能在一個Mozilla基於瀏覽器。

使用簡單的異常處理,你也許能得到您想要的行爲:

try { 
    car().start(); //vrooom 
    car().growBeard(); 
} 
catch (e) { 
    if (e instanceof TypeError) { 
     alert(e.message); 
    } 
} 
+0

我正試圖處理這種情況,我不知道可以調用什麼方法。最終,我想讓catchall方法根據方法的名稱設置屬性。也就是說,car()。color('red')可能會設置car.color ='red' – nebulous 2011-03-24 17:09:37

+0

謝謝Mark,如果它是標準的話,那就是票。希望有另一條路線可能與異常處理,這是與大多數瀏覽器兼容。 – nebulous 2011-03-24 17:32:01

+0

@nebulous,我添加了一個簡單的'try {} catch {}' – 2011-03-24 17:44:03

0

的新望ES6代理對象會有所幫助:(從here複製示例代碼)

obj = new Proxy({}, { 
    get: function(target, prop) { 
    if (target[prop] === undefined) 
     return function() { 
     console.log('an otherwise undefined function!!'); 
     }; 
    else 
     return target[prop]; 
    } 
}); 
obj.f() // "an otherwise undefined function!!" 
obj.l = function() { console.log(45); }; 
obj.l(); // "45" 

代理對象unshimmable。瀏覽器支持很好,但還不完善,請參閱http://caniuse.com/#feat=proxy