判斷一個實例是否存在某個屬性的方法使用 "in"this
var Student = { name: "Robot", height: 1.2, sex: "male", run: function(){ console.log(this.name+" is running"); } }; function createStudent(name) { var s = Object.create(Student); s.name = name; return s; }
"in"判斷是否存在實例屬性中,不管是實例本身有的,或者繼承而來的。spa
"name" in xiaoming; //truecode
"name" in Student; //trueblog
"run" in xiaoming;//true繼承
"run" in Student; //trueio
若是隻是要判斷是否實例自身擁有的,而不是繼承而來的,要使用實例的hasOwnProperty()方法。console
xiaoming.hasOwnProperty("name"); //truefunction
xiaoming.hasOwnProperty("run"); //falseclass