[英]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.