Write a function that checks if a given value is an instance of a given class or superclass. For this problem, an object is considered an instance of a given class if that object has access to that class's methods.
There are no constraints on the data types that can be passed to the function. For example, the value or the class could be undefined.
寫一個函數來檢查某物件是否可存取該類別的方法。
第一次
var checkIfInstanceOf = function(obj, classFunction) {
if(obj.constructor === classFunction) return true;
else return false;
};
我使用了.constructor去比對是不是classFunction的建構子。
但在case2的時候錯了。
Input:
() => { class Animal {};
class Dog extends Animal {};
return checkIfInstanceOf(new Dog(), Animal); }
我回傳了false。
題目下面有幾個提示:
In Javascript, inheritance is achieved with the prototype chain.
You can get the prototype of an object with the Object.getPrototypeOf(obj) function. Alternatively, you can code obj['proto'].
You can compare an object's proto with classFunction.prototype.
Traverse the entire prototype chain until you find a match.
在第一個提示提到了原型鏈。
所以應該是要追溯到最原始的型態取比較。
而第二題是提到了「Object.getPrototypeOf(obj)」
繼續試試
var checkIfInstanceOf = function(obj, classFunction) {
while (obj != null) {
if (obj.constructor === classFunction) {
return true;
}
obj = Object.getPrototypeOf(obj);
}
return false;
};