我有三种创建对象的方法:
function createC() {
function Person(name){
this.name = name;
this.getName = function(){
return this.name;
};
}
return new Person("Diego");
}
function createD() {
function Person() { };
Person.prototype.name = "Diego";
Person.prototype.getName = function () {
return this.name;
};
return new Person();
}
function createE() {
return Object.create(Object.prototype, {
name: { value: "Diego" },
getName: { value: function () { return this.name; } }
});
}
每个对象中的三个对象可以作为相同的对象使用,但是在检查它们自己的属性时会产生不同的结果。这是我为检查属性而编写的函数:
function checkOwnProperies(obj, name) {
console.log('check object ' + name + '\'s own properties:');
var bIn = false;
for (var v in obj) {
bIn = true;
if (obj.hasOwnProperty(v)) {
console.log('Yes! Found own property: ' + v);
}
else {
console.log('Found a property, but it\'s not own: ' + v);
}
}
if (!bIn)
console.log("Didn\'t find any members in " + name + '!');
}
我得到的结果:
oC name: Diego
oD name: Diego
oE name: Diego
check object oC's own properties:
Yes! Found own property: name
Yes! Found own property: getName
check object oD's own properties:
Found a property, but it's not own: name
Found a property, but it's not own: getName
check object oE's own properties:
Didn't find any members in oE!
完整片段:http ://codepen.io/anon/pen/homGx
有人可以解释为什么有区别吗?