سؤال

What's the best way to check the type for objects created by Object.create or literal, for example the following code. I want to make sure the arguments to the function is safe to use. Maybe I shouldn't check the type of arguments, but check whether the properties the function uses are not undefined. But it seems very tedious to do so. What's the best approach, thanks.

var base = {
    name : "abc"
};

var child = Object.create(base);
do_something = function(o) {
    if (typeof(o) === "base") { // will not work
      ...
    }
}
هل كانت مفيدة؟

المحلول

typeof can only return the base type like, object, strirng, number, undefined.

typeof o === "object"

instanceof can be used if you are inheriting from the base class. Eg here MDN

function Base() {
  this.name = "abc";
}
var child = new Base();
var a = child instanceof Base;  //true

instance of expects the format <object> insanceof <function>


You can use isPrototypeOf() when inheriting using Object.create()

var base = {name; "abc"};
var child = Object.create(base);

base.isPrototypeOf(child);

More info can be read here: Mozilla Developer Network: isPrototypeOf


To check if there exists an object o with the attribute name non empty, you can do

if(typeof o === "object" && typeof o.name !== "undefined")

A shorthand can be used, if name will not hold falsy values like 0

if(o && o.name)

نصائح أخرى

In your code base is a variable not a type, In JavaScript function are treated as classes if you want base type then create a function and initialize it and then use instanceof that will give you base.

Try this way using instanceof:

var base = function(){
    name : "abc"
};

var o = new base();
alert(o instanceof base); // true

Here is JsFiddle

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top