特定のオブジェクトのメソッドが見つからない場合、別のメソッドにフォールバックできますか?
私が持っていると言う(アイデアを得るためだけに)
var phoneCall new function() {
function toMom() {
}
function catchAll() {
}
}
q = new phoneCall;
q.toMom();
q.toDad() //should fire phoneCall.catchAll();
特定のオブジェクトのメソッドが見つからない場合、別のメソッドにフォールバックできますか?
私が持っていると言う(アイデアを得るためだけに)
var phoneCall new function() {
function toMom() {
}
function catchAll() {
}
}
q = new phoneCall;
q.toMom();
q.toDad() //should fire phoneCall.catchAll();
いいえ-クロスブラウザの方法ではありません。Firefoxと他のいくつかのエンジンにはこれを行うためのアプローチがありますが、Chrome、IEなどでは機能しません。プロキシは最終的にこのような機能を許可しますが、それはまだエンジン採用の初期段階です。
var phoneCall = {
to: function(whom) {
(phoneCall.people[whom] || phoneCall.catchAll)();
},
people: {
mom: function() {
// call mom functionality
}
},
catchAll: function() {
// generic call functionality
}
};
phoneCall.to('mom');
phoneCall.to('dad'); // invokes catchAll
ゲッター パターンを使用します。
var myObject = (function() {
var methods = {
method1: function () {
console.log('method1 called');
},
method2: function () {
console.log('method2 called');
},
defaultMethod: function () {
console.log('defaultMethod called');
}
};
var get = function (name) {
if (methods.hasOwnProperty(name)) {
return methods[name];
} else {
return methods.defaultMethod;
}
};
return {
get: get
};
}());
次のコードは、最初のメソッドが存在しない場合にフォールバック メソッドを呼び出す方法を示しています。
q = {};
q.toDad = function() {
console.log("to dad");
}
(q.toMom || q.toDad)(); // Will output "to dad" to the console
q.toMom = function() {
console.log("to mom");
}
(q.toMom || q.toDad)(); // Will output "to mom" to the console
あなたはそのようなことをすることができます:
q.toDad() || q.catchAll();
編集:
ユーザーjmar77は、関数自体ではなく関数の結果を返しているため、このコードが無効であることについて正しいです...私の悪い。更新されたコードは次のとおりです。
function phoneCall() {
this.toMom = function() {
console.log('Mom was called.');
}
this.catchAll = function() {
console.log('Catch all was called');
}
}
q = new phoneCall();
q.toMom();
q.toDad ? q.toDad() : q.catchAll();