ArticleDirectory
- Javascript methods that are easy to mix: hasownproperty and isprototypeof
Javascript methods that are easy to mix: hasownproperty and isprototypeof
October 10, 2011 by Ryan | 1 commentviews: 95 today views: 1
If it is easy to mix up, it is actually a poor grasp. Don't be surprised. I have always been reading books by duck. Finally, the conversion was completed, and the words were carefully read. I wrote a similar article earlier.
Hasownproperty
Before introducing this method, let's talk about the problem we encountered today. We usually need to loop through an array. What should we do?
There are two solutions available: For and... In, the question is, what are the differences between the two methods?
To answer this question, we only need to look at the example:
1
2
3
4
5
6
7
8
9
10
11
12
13
Array. Prototype. Foo =
"Somevalue"
;
VaR
Array = [
'A'
,
'B'
,
'C'
];
For
(
VaR
I
In
Array ){
Alert (array [I]);
}
Syntax
For
(Prop
In
Object ){......}
// For in syntax:
// Obviously, this will enumerate all method attributes, and the result will be a, B, c, somevalue
// While for only loops a, B, c
This is what others have said, without the benefit of for in. In the prototype library, the entire library is based on the extended object, which makes it easy to make mistakes. Of course, I have not studied the prototype library, but I have read a littleCode. Is there any way for it to loop through its own attributes?
2011-12-09 supplement:
For in loops through all functions and prototype properties of the object, and the hasownproperty method does not search for the prototype chain.
The following is the first hasownproperty we introduced today:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
VaR
OBJ = {
""
: 1,
"B"
: 2,
"C"
: 3
};
For
(
VaR
Prop
In
OBJ ){
If
(Obj. hasownproperty (PROP )){
// Or if (object. Prototype. hasownproperty. Call (OBJ, Prop) for safety...
Alert (
"Prop :"
+ Prop +
"Value :"
+ OBJ [prop])
}
}
// Syntax
// Obj. hasownproperty (PROP)
// Due to time issues, I have copied a piece of code. After this for in is judged by a hasownproperty, we can accurately find the desired result.
// It also contains an object. Prototype. hasownproperty. Call (OBJ, Prop )),
// Probably because in the prototype chain, the top-level method should be the safest and not contaminated.
Isprototypeof
1
2
Syntax
Prototype. isprototypeof (object)
1
2
3
4
5
6
7
8
9
10
11
12
13
Function
Foo (){
This
. Name =
'Foo'
;
};
Function
Bar (){};
Bar. Prototype =
New
Foo ();
VaR
Goo =
New
Bar ();
Console. Log (goo. Name );
// Foo
Console. Log (bar. Prototype. isprototypeof (goo ));
// True
// If the current object goo exists in the bar prototype chain, the isprototypeof method returns true.
Categories: mypost | tags: hasownproperty, isprototypeof | permalink
Address: http://www.coolicer.com/2011/10/10/javascript-hasownproperty-and-isprototypeof.html