function Shape() {
    this.name = "Generic";
    this.draw = function() {
        return "Drawing " + this.name + " Shape";
    };
}
function welcomeMessage()
{
    var shape1 = new Shape();
    //alert(shape1.draw());
    alert(shape1.hasOwnProperty(name));  //this is returning false
}
.welcomeMessage呼吁这个body.onload事件.
我期望shape1.hasOwnProperty(name)返回true,但它返回false.
什么是正确的行为?
我试图了解hasOwnProperty()在迭代对象键时使用check的目标。据我所知,在两种情况下,都会为每个对象属性(不是更多,也不是更少)执行迭代:有hasOwnProperty()或没有。例如,在下面的代码中,带hasOwnProperty()检查和不带检查的结果是一样的:
const obj = {
  prop1: [],
  prop2: {},
  prop3: "",
  prop4: 0,
  prop5: null,
  prop6: undefined
}
const resultWithHasOwnProperty = [];
const resultWithoutHasOwnProperty = [];
for(key in obj) {
  if(obj.hasOwnProperty(key)) {
    resultWithHasOwnProperty.push(obj[key])
  }
}
for(key in obj) {
  resultWithoutHasOwnProperty.push(obj[key])
}
console.log("Result WITH hasOwnProperty check: ", resultWithHasOwnProperty);
console.log("Result WITHOUT hasOwnProperty check: ", resultWithoutHasOwnProperty);所以我的问题是:为什么以及何时应该使用hasOwnProperty()检查?
我将重新表述我的问题:如果不hasOwnProperty()检查,我们将始终遍历所有现有属性?
请注意,这个问题并不是真正的重复。
在这篇文章中如何显示一个对象的所有方法?,它说“您可以使用 Object.getOwnPropertyNames() 来获取属于一个对象的所有属性,无论是否可枚举”。通过示例,我们可以看到所有属性都包括Math列出的对象的方法。我尝试并得到了相同的结果。
然后我尝试定义我自己的对象并以相同的方式列出它的属性,但为什么没有列出方法?例如console.log(Object.getOwnPropertyNames(animal))为什么它只返回["name", "weight"]而不包括"eat", "sleep" and wakeUp?
function Animal(name, weight) {
    this.name = name;
    this.weight = weight;
}
Animal.prototype.eat = function() {
    return `${this.name} is eating!`;
}
Animal.prototype.sleep = function() {
    return `${this.name} is going to sleep!`;
}
Animal.prototype.wakeUp = function() {
    return `${this.name} is waking up!`;
}
var animal = new Animal('Kitten', '5Kg');
console.log(Object.getOwnPropertyNames(animal));  // ["name", "weight"]另一个例子是,为什么下面的一个返回属于超类的属性,因为它是Triangle从Shape …
javascript ×3