gpt4 book ai didi

javascript - 如何确保函数/方法参数属于特定类型?

转载 作者:行者123 更新时间:2023-11-30 16:05:41 26 4
gpt4 key购买 nike

是否可以确保函数/方法参数属于特定类型?

例如,我有一个简单的 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);
};

有什么想法吗?

最佳答案

在这种特殊情况下,是的,您有两个选择:

  1. 实例:

    if (health instanceof Health) {
    // It's a Health object *OR* a derivative of one
    }

    从技术上讲,instanceof 检查的是 Health.prototype 所指的对象是否在 health 的原型(prototype)链中。

  2. 检查构造函数

    if (health.constructor === Health) {
    // Its `constructor` is `Health`, which usually (but not necessarily)
    // means it was constructed via Health
    }

    请注意,这很容易伪造:let a = {}; a.constructor = 健康;

通常你可能想使用前者,因为 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);
}

关于javascript - 如何确保函数/方法参数属于特定类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37099879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com