检查这是否是JavaScript中new google.maps.LatLng的实例

Check if this is an instance of new google.maps.LatLng in JavaScript

本文关键字:maps LatLng 实例 google new 是否是 JavaScript 检查      更新时间:2023-09-26

我有我的JS对象。

function Foo() { 
    this.bar = new google.maps.LatLng(12, 34);
}

我还做了一个getter和setter:

Foo.prototype.SetBar = function(bar_arg) {
    this.bar = bar_arg;
}

Foo.prototype.GetBar = function() {
    return this.bar;
};

如何强制用户只提供google.maps.LatLng对象作为bar_arg ?

换句话说,如果用户将调用this.setBar('i am a string')而不是this.setBar(new google.maps.LatLng(56, 78)),我想抛出一个异常来执行特定的操作。安装是一个好主意吗?如果是,我该如何检查?

if ( ! bar_arg instanceof google.maps.LatLng) { //throw new... }

还是

if ( ! bar_arg instanceof LatLng) { //throw new... }

显然Google Maps API被加载了

你对instanceof的看法是正确的。

事实上,稍微修改一下你的尝试:

if (!(bar_arg instanceof google.maps.LatLng)) { //throw new... }