javascript 中的 hasOwnProperty
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2600085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
hasOwnProperty in javascript
提问by Thiyaneshwaran S
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
}
.welcomeMessagecalled on the body.onloadevent.
.welcomeMessage呼吁该body.onload事件。
I expected shape1.hasOwnProperty(name)to return true, but its returning false.
我希望shape1.hasOwnProperty(name)返回 true,但它返回 false。
What is the correct behavior?
什么是正确的行为?
回答by SLaks
hasOwnPropertyis a normal Javascript function that takes a string argument.
hasOwnProperty是一个普通的 Javascript 函数,它接受一个字符串参数。
When you call shape1.hasOwnProperty(name)you are passing it the value of the namevariable (which doesn't exist), just as it would if you wrote alert(name).
当您调用时,shape1.hasOwnProperty(name)您将name变量的值(不存在)传递给它,就像您编写alert(name).
You need to call hasOwnPropertywith a string containing name, like this: shape1.hasOwnProperty("name").
你需要调用hasOwnProperty包含一个字符串name,像这样:shape1.hasOwnProperty("name")。
回答by Pablo Cabrera
hasOwnPropertyexpects the property name as a string, so it would be shape1.hasOwnProperty("name")
hasOwnProperty期望属性名称为字符串,因此它将是 shape1.hasOwnProperty("name")
回答by Ernelli
Try this:
尝试这个:
function welcomeMessage()
{
var shape1 = new Shape();
//alert(shape1.draw());
alert(shape1.hasOwnProperty("name"));
}
When working with reflection in JavaScript, member objects are always refered to as the name as a string. For example:
在 JavaScript 中使用反射时,成员对象总是作为字符串的名称引用。例如:
for(i in obj) { ... }
for(i in obj) { ... }
The loop iterator i will be hold a string value with the name of the property. To use that in code you have to address the property using the array operator like this:
循环迭代器 i 将保存一个带有属性名称的字符串值。要在代码中使用它,您必须使用数组运算符来处理属性,如下所示:
for(i in obj) {
alert("The value of obj." + i + " = " + obj[i]);
}
回答by KARTHIKEYAN.A
hasOwnProperty()is nice property to validate object keys. example:
hasOwnProperty()是验证对象键的好属性。 例子:
var obj = {a:1,b:2};
obj.hasOwnProperty('a') // true

