[英]How can I ensure a function/method param is of a certian type?
是否可以確保功能/方法參數為某種類型?
例如,我有一個簡單的Character類,可以接受可選的Health
對象。 是否可以檢查該參數是否為Health
類型? 當應用程序需要Health
對象時,我不希望使用者傳遞一個整數。
let Character = function(health) {
if(typeof health === 'undefined')
this.health = new Health(100);
else
this.health = health;
};
Character.prototype.hit = function(hitPoints) {
this.health.subtract(hitPoints);
};
有任何想法嗎?
在這種特殊情況下,是的,您有兩個選擇:
instanceof
:
if (health instanceof Health) { // It's a Health object *OR* a derivative of one }
從技術上講, instanceof
檢查的是Health.prototype
引用的對象是否在health
的原型鏈中。
檢查constructor
if (health.constructor === Health) { // Its `constructor` is `Health`, which usually (but not necessarily) // means it was constructed via Health }
注意,這很容易偽造: let a = {}; a.constructor = Health;
let a = {}; a.constructor = Health;
通常,您可能希望使用前者,因為A)它允許Health
子類型,並且B)當使用ES5和更早的語法進行繼承層次結構時, 許多人忘記了修復constructor
,並且最終指向了功能錯誤。
ES5語法示例:
var Health = function() { }; var PhysicalHealth = function() { Health.call(this); }; PhysicalHealth.prototype = Object.create(Health.prototype); PhysicalHealth.prototype.constructor = PhysicalHealth; var h = new PhysicalHealth(); log(h instanceof Health); // true log(h.constructor == Health); // false function log(msg) { var p = document.createElement('p'); p.appendChild(document.createTextNode(msg)); document.body.appendChild(p); }
或使用ES2015(ES6):
class Health { } class PhysicalHealth extends Health { } let h = new PhysicalHealth(); log(h instanceof Health); // true log(h.constructor == Health); // false function log(msg) { let p = document.createElement('p'); p.appendChild(document.createTextNode(msg)); document.body.appendChild(p); }
簡短的做法...
let character = function(health) { this.health = (health instanceof Health) ? health : new Health(100); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.