JQuery button problem

A

Andre

Hello everybody,

I have a problem with jQuery.

At moment of opening the page, he doesn't contain any button but the javascript
for the button is loaded.

When the user execute some function, I must add a button on the page.

I use the command :

$("#t1").html('<input type="button" name="bt_Save" id="bt_Save" value="Save"
/>');

The code function well. The button appear correctly. But when I clic on the
button, nothing happens. Such as no event does exist.

in the javascript, I write the following code (in the header of the page):

jQuery(document).ready(function(){
jQuery("#bt_Save").click(function(){
alert('Hello');
});
});

Have you some ideas to resolve the problem?

I use the JQuery version : 1.4.2

Thank you in advance
Best regards

Andre
 
R

Robin Rattay

Am 16.04.2010 10:40, schrieb Andre:
I have a problem with jQuery.

While I don't agree with many voices in this group, that jQuery is the
devil, I do believe, that you make sure that it is the right tool, and
in this case I would say it more efficent to use regular DOM methods to
do this:

var b = document.createElement("input");
b.type = "button";
b.value = "Save";
b.onclick = function() {alert('Hello');};
document.getElementById("t1").appendChild(b);

(Untested und lacking error checking)
$("#t1").html('<input type="button" name="bt_Save" id="bt_Save" value="Save"
/>');

When do you do this?
jQuery(document).ready(function(){
jQuery("#bt_Save").click(function(){
alert('Hello');
});
});

Yre you sure this happens after adding the button? Why don't you add the
button and set the handler at the same time? For example:

$("#t1").html('<input type="button" name="bt_Save" id="bt_Save"
value="Save"/>').find("input").click(function(){
alert('Hello');
});

Robin
 
S

S.T.

Hello everybody,

I have a problem with jQuery.

At moment of opening the page, he doesn't contain any button but the javascript
for the button is loaded.

When the user execute some function, I must add a button on the page.

I use the command :

$("#t1").html('<input type="button" name="bt_Save" id="bt_Save" value="Save"
/>');

The code function well. The button appear correctly. But when I clic on the
button, nothing happens. Such as no event does exist.

in the javascript, I write the following code (in the header of the page):

jQuery(document).ready(function(){
jQuery("#bt_Save").click(function(){
alert('Hello');
});
});

Have you some ideas to resolve the problem?


Sounds like the events are binding before the button is making it in the
DOM. Try either of the event delegation methods, i.e. live():

jQuery("#bt_Save").live("click",function(){
alert('Hello');
});

.... or the newer delegate() in 1.4.2, which can have performance
benefits in some instances (though I don't care for the format).

jQuery("#t1").delegate("#bt_Save", "click", function(){
alert('Hello');
});
 
G

Garrett Smith

Robin said:
Am 16.04.2010 10:40, schrieb Andre:

While I don't agree with many voices in this group, that jQuery is the
devil, I do believe, that you make sure that it is the right tool, and
in this case I would say it more efficent to use regular DOM methods to
do this:

Using jQuery to do what the OP wants to do is senseless.

Where has jQuery been called the devil? jQuery is magic.
var b = document.createElement("input");
b.type = "button";
b.value = "Save";
b.onclick = function() {alert('Hello');};
document.getElementById("t1").appendChild(b);

Either set `b = null` or do not put `b` in scope of the assigned onclick
handler, as in:- b.onclick = buttonClickHandler - and define
buttonClickHandler in containing scope.

function makeButton() {
var b = document.createElement("input");
// ...
b.onclick = buttonClickHandler;
}
(Untested und lacking error checking)


When do you do this?

If that happens after the ready function has been called, then it isn't
going to have much effect, is it?
Yre you sure this happens after adding the button? Why don't you add the
button and set the handler at the same time? For example:

$("#t1").html('<input type="button" name="bt_Save" id="bt_Save"
value="Save"/>').find("input").click(function(){
alert('Hello');
});

That is very inefficient way of solving the problem and relies on jquery.

The interface provided by jquery is complicated. Using that introduces
complexity at no additional benefit.
 
T

Thomas 'PointedEars' Lahn

Garrett said:
Using jQuery to do what the OP wants to do is senseless.
ACK

Where has jQuery been called the devil? jQuery is magic.

*Black* magic at that.


PointedEars
 
G

Garrett Smith

Thomas said:
[...]
Where has jQuery been called the devil? jQuery is magic.

*Black* magic at that.

No magic is programming; that was a joke.

I'm poking fun at the documentation pages of jQuery.com, which uses "the
magic of jquery" to describe, IIRC, function chaining.
 
D

David Mark

S.T. said:
Sounds like the events are binding before the button is making it in the
DOM. Try either of the event delegation methods, i.e. live():

jQuery("#bt_Save").live("click",function(){
alert('Hello');
});

... or the newer delegate() in 1.4.2, which can have performance
benefits in some instances (though I don't care for the format).

jQuery("#t1").delegate("#bt_Save", "click", function(){
alert('Hello');
});

This is all ridiculous. Why on earth would you fumble around with a
black box (with potentially explosive contents) when you don't have to?
The OP is trying to make a button click work. (!)

This is why jQuery is never the right "tool" for the job (unless the job
is losing your job for grossly incompetent decision-making).
 
A

Asen Bozhilov

Garrett said:
I'm poking fun at the documentation pages of jQuery.com, which uses "the
magic of jquery" to describe, IIRC, function chaining.

They often use the word "magic". That is marketing strategy. There is
many books which explain jQuery or better to say, those books are for
jQuery propaganda. If you open jquery.com you can see a bold
sentence:

| jQuery is designed to change the way that you write JavaScript.

If I am looking for framework for specific application and I see that
sentence I will hit the close button and gone away. If someone want to
change the language, he is free to implement own language. If they try
to change my style of programming that mean more time for development
of my project. And of course that changes do not guarantee nothing.
They not guarantee real improvements and unfortunately they are not
provide any improvements. They only provide excuses for unreasonable
development. Does anybody explain the meaning of:

jQuery.isPlainObject

What should mean "plain object"? In theirs documentation is written:

| Description: Check to see if an object is a plain object
| (created using "{}" or "new Object").

That is just native object for which next object in prototype chain is
object referred by Object.prototype. Why they need to recognize
prototype chain of native objects, especially in this way? What non-
generic can do it on Object instance to need recognize?
Could someone explain these question.
 
G

Garrett Smith

Asen said:
They often use the word "magic". That is marketing strategy. There is
many books which explain jQuery or better to say, those books are for
jQuery propaganda. If you open jquery.com you can see a bold
sentence:

| jQuery is designed to change the way that you write JavaScript.

If I am looking for framework for specific application and I see that
sentence I will hit the close button and gone away. If someone want to
change the language, he is free to implement own language. If they try
to change my style of programming that mean more time for development
of my project. And of course that changes do not guarantee nothing.
They not guarantee real improvements and unfortunately they are not
provide any improvements. They only provide excuses for unreasonable
development. Does anybody explain the meaning of:

jQuery.isPlainObject

What should mean "plain object"?

No fairy dust?

In theirs documentation is written:
| Description: Check to see if an object is a plain object
| (created using "{}" or "new Object").

That is just native object for which next object in prototype chain is

The description taken literally does not state anything about the
prototype chain. The code comment does, mention that.
object referred by Object.prototype. Why they need to recognize
prototype chain of native objects, especially in this way? What non-
generic can do it on Object instance to need recognize?
Could someone explain these question.
Good question. I probably can't full answer that without spending well
over an hour on it. Most jQuery methods are long and complicated.

The first occurrence of `jQuery.isPlainObject` occurs in the constructor
for jQuery, `init`, which is defined in the prototype of the jQuery
function (still there, oddly).

Take a look at that `jQuery.prototype.init` and just count the number of
loops and `if` and `else` statements.

| init: function( selector, context ) {
| var match, elem, ret, doc;
|
| // Handle $(""), $(null), or $(undefined)
| if ( !selector ) {
| return this;
| }
|
| // Handle $(DOMElement)
| if ( selector.nodeType ) {
| this.context = this[0] = selector;
| this.length = 1;
| return this;
| }
|
| // The body element only exists once, optimize finding it
| if ( selector === "body" && !context ) {
| this.context = document;
| this[0] = document.body;
| this.selector = "body";
| this.length = 1;
| return this;
| }
|
| // Handle HTML strings
| if ( typeof selector === "string" ) {
| // Are we dealing with HTML string or an ID?
| match = quickExpr.exec( selector );
|
| // Verify a match, and that no context was specified for #id
| if ( match && (match[1] || !context) ) {
|
| // HANDLE: $(html) -> $(array)
| if ( match[1] ) {
| doc = (context ? context.ownerDocument || context :
| document);
|
| // If a single string is passed in and it's a single tag
| // just do a createElement and skip the rest
| ret = rsingleTag.exec( selector );
|
| if ( ret ) {
| if ( jQuery.isPlainObject( context ) ) {
| selector = [ document.createElement( ret[1] ) ];
| jQuery.fn.attr.call( selector, context, true );
|
| } else {
| selector = [ doc.createElement( ret[1] ) ];
| }
|
| } else {
| ret = buildFragment( [ match[1] ], [ doc ] );
| selector = (ret.cacheable ? ret.fragment.cloneNode(true) :
| ret.fragment).childNodes;
| }
|
| return jQuery.merge( this, selector );
|
| // HANDLE: $("#id")
| } else {
| elem = document.getElementById( match[2] );
|
| if ( elem ) {
| // Handle the case where IE and Opera return items
| // by name instead of ID
| if ( elem.id !== match[2] ) {
| return rootjQuery.find( selector );
| }|
|
| // Otherwise, we inject the element directly into the jQuery object
| this.length = 1;
| this[0] = elem;
| }
|
| this.context = document;
| this.selector = selector;
| return this;
| }
|
| // HANDLE: $("TAG")
| } else if ( !context && /^\w+$/.test( selector ) ) {
| this.selector = selector;
| this.context = document;
| selector = document.getElementsByTagName( selector );
| return jQuery.merge( this, selector );
|
| // HANDLE: $(expr, $(...))
| } else if ( !context || context.jquery ) {
| return (context || rootjQuery).find( selector );
|
| // HANDLE: $(expr, context)
| // (which is just equivalent to: $(context).find(expr)
| } else {
| return jQuery( context ).find( selector );
| }
|
| // HANDLE: $(function)
| // Shortcut for document ready
| } else if ( jQuery.isFunction( selector ) ) {
| return rootjQuery.ready( selector );
| }
|
| if (selector.selector !== undefined) {
| this.selector = selector.selector;
| this.context = selector.context;
| }
|
| return jQuery.makeArray( selector, this );
| },

for............0
if............14
else...........7

No for loops in that method, but a combined total of 21 if and else
statements over 104 SLOC. That method, which is complicated in and of
itself, calls several other methods that are also complicated.

Trying to figure the whole mess out requires a map. Of course, the code
does not have to be written that way at all.

The method's contract is part of a public interface and so that,
unfortunately, cannot be easily changed.

The method could, however, be refactored to dispatch the functionality
to different hidden functions, as in:

if ( selector.nodeType ) {
handleDomElement( selector );
}

- which would help shorten the method up and make it easier to read, but
it would not alleviate the inherent complexity in the design of that
methods signature so it would still take a good long look to figure out
all that it is doing and why.

Complexity makes changes and refactoring less safe. Sometimes it can be
avoided. Dynamic overloading is a design decision that adds complexity.

In addition to adding complexity, dynamic overloading requires various
amounts of complicated and often nonstandard checks, particularly around
host objects.

So it's not magic. It is needlessly complex API design that has all the
consequences that can be expected that.
 
R

RobG

Does anybody explain the meaning of:

jQuery.isPlainObject

What should mean "plain object"? In theirs documentation is written:

| Description: Check to see if an object is a plain object
| (created using "{}" or "new Object").

That is just native object for which next object in prototype chain is
object referred by Object.prototype. Why they need to recognize
prototype chain of native objects, especially in this way? What non-
generic can do it on Object instance to need recognize?
Could someone explain these question.

Many jQuery methods are overloaded, they do different things if passed
nothing, an object, a string, an array, an element, and so on. Trying
to work out how or why the code does what it does makes me give up in
frustration.

For example, in the - extend - function, isPlainObject is used as
follows (my wrapping):

| // Recurse if we're merging object literal values or arrays
| if ( deep && copy && ( jQuery.isPlainObject(copy) ||
| jQuery.isArray(copy) ) ) {
| var clone = src && ( jQuery.isPlainObject(src) ||
| jQuery.isArray(src) ) ? src
| : jQuery.isArray(copy) ? [] : {};

It only seems to be used in one other place, which is the - init -
function:

| if ( jQuery.isPlainObject( context ) ) {
| selector = [ document.createElement( ret[1] ) ];
| jQuery.fn.attr.call( selector, context, true );
|
| } else {
| selector = [ doc.createElement( ret[1] ) ];
| }

so if "context" is a "plainObject" then it does one thing, if it's
anything else it does something different.

Within the expression creating the function, there is the following
comment and code:

| isPlainObject: function( obj ) {
| ...
| // Own properties are enumerated firstly, so to speed up,
| // if last one is own, then all properties are own.
| var key;
| for ( key in obj ) {
| }
| return key === undefined || hasOwnProperty.call( obj, key );
| },

where - hasOwnProperty - is a global variable that is a reference to
Object.prototype.hasOwnProperty in Firefox but in IE 6 returns
undefined.

Presumably if obj is a native object, then it will have a
hasOwnProperty method (this method is missing in IE 5 and Safari until
v 2.0.2, but jQuery doesn't support them) and the method could be
called as:

obj.hasOwnProperty( key );

Anyhow, this part of the logic assumes properties are returned
according to some fixed order that is expressly not enforced by
ECMA-262 ed 3:

| 4.2 Language Overview
| ... An ECMAScript object is an unordered collection of
properties ...

| 4.3.3 Object
| An object is a member of the type Object. It is an unordered
collection | of properties...

| 12.6.4 The for-in Statement
| ...
| The mechanics of enumerating the properties ... is
| implementation dependent. The order of enumeration is
| defined by the object

So there is no reason to believe that every implementation will
enumerate own properties first and it can be demonstrated to be a
false assumption in IE 6 at least:

Object.prototype.bar = 'bar';
var obj = {};
obj.foo = 'foo';

for (var k in obj) {}
alert(k); // shows 'foo' in IE 6
// shows 'bar' in Firefox

so in IE, the inherited property was enumerated before the assigned
one, in Firefox it is enumerated after.

The significance of all enumerable properties being own properties is,
presumably, that they were added by assigning them directly to the
object and therefore it hasn't inherited any from its [[prototype]].
That logic is only supported by observation in a small number of
browsers and is wrong in one of jQuery's supported set.
 
G

Garrett Smith

RobG said:
Does anybody explain the meaning of:

jQuery.isPlainObject

What should mean "plain object"? In theirs documentation is written:

| Description: Check to see if an object is a plain object
| (created using "{}" or "new Object").

That is just native object for which next object in prototype chain is
object referred by Object.prototype. Why they need to recognize
prototype chain of native objects, especially in this way? What non-
generic can do it on Object instance to need recognize?
Could someone explain these question.

Many jQuery methods are overloaded, they do different things if passed
nothing, an object, a string, an array, an element, and so on. Trying
to work out how or why the code does what it does makes me give up in
frustration.

For example, in the - extend - function, isPlainObject is used as
follows (my wrapping):

| // Recurse if we're merging object literal values or arrays
| if ( deep && copy && ( jQuery.isPlainObject(copy) ||
| jQuery.isArray(copy) ) ) {
| var clone = src && ( jQuery.isPlainObject(src) ||
| jQuery.isArray(src) ) ? src
| : jQuery.isArray(copy) ? [] : {};

It only seems to be used in one other place, which is the - init -
function:

| if ( jQuery.isPlainObject( context ) ) {
| selector = [ document.createElement( ret[1] ) ];
| jQuery.fn.attr.call( selector, context, true );
|
| } else {
| selector = [ doc.createElement( ret[1] ) ];
| }

so if "context" is a "plainObject" then it does one thing, if it's
anything else it does something different.

Within the expression creating the function, there is the following
comment and code:

| isPlainObject: function( obj ) {
| ...
| // Own properties are enumerated firstly, so to speed up,
| // if last one is own, then all properties are own.
| var key;
| for ( key in obj ) {
| }
| return key === undefined || hasOwnProperty.call( obj, key );
| },

where - hasOwnProperty - is a global variable that is a reference to
Object.prototype.hasOwnProperty in Firefox but in IE 6 returns
undefined.

No, `hasOwnProperty` is an identifier in containing scope. It has the
value of `Object.prototype.hasOwnProperty`:

| // Save a reference to some core methods
| toString = Object.prototype.toString,
| hasOwnProperty = Object.prototype.hasOwnProperty,

[...]

That code will reveal a quirk in Blackberry9000. BB9k creates, for the
activation object (AO), an Object object, and so for scope chain and
identifier resolution, the property will be resolved on the AO's
[[Prototype]], Object.prototype. It's a bad feature, but AFAICT it is
standards compliant with ECMA-262 edition 3.

Discussed here:
http://groups.google.com/group/comp.lang.javascript/msg/1414bf1c85e0afeb?dmode=source

Example:
<http://github.com/GarrettS/ape-javascript-library/blob/master/adhoctest/activationo.html>

Explanation:
<http://yura.thinkweb2.com/named-function-expressions/#activation-object-in-blackberry-browser>

[explanation of enumeration order]

I should have investigated that one. In fact I thought that that code
comment was wrong. I just was focusing on getting the code formatted and
counting `if` and `else` statements.
Object.prototype.bar = 'bar';
var obj = {};
obj.foo = 'foo';

for (var k in obj) {}
alert(k); // shows 'foo' in IE 6
// shows 'bar' in Firefox

so in IE, the inherited property was enumerated before the assigned
one, in Firefox it is enumerated after.

Result:
IE 6, 7, 8:
b, a
Firefox 2, 3.6, Opera 10.5:
a, b

Example code:
function X(){this.a=1;}
X.prototype={b:2});
var x = new X;
for(var prop in x)
alert(prop);
The significance of all enumerable properties being own properties is,
presumably, that they were added by assigning them directly to the
object and therefore it hasn't inherited any from its [[prototype]].
That logic is only supported by observation in a small number of
browsers and is wrong in one of jQuery's supported set.

Three versions of IE. That counts as three browsers.

The result is not surprising. Relying on nonstandard behavior is risky.
Its crazy to check that in and not even test it though. Maybe a there
was a test error?

They could have checked the result of calling `hasOwnProperty` in the
body of the loop. They don't support Safari 2, I believe, so they could
get away with that. For Safari 2, they could either provide a fallback
or could at the very least, provide something that wont throw errors, e.g.:

var hasOwnProperty = ({}).hasOwnProperty || Function.prototype;

- and calling hasOwnProperty in Safari 2 wouldd result in the value
`undefined` being returned, instead of an error being thrown. Not a good
solution, but at least no errors in Safari 2.

Another solution for checking hasOwnProperty is to check, where
supported, the `__proto__`

Thanks for the detailed explanation.
 
M

Michael Haufe (\TNO\)

Does anybody explain the meaning of:

jQuery.isPlainObject

What should mean "plain object"?

There was a method posted on a blog a few months ago (I can't find the
original article) that showed an approach to determining if an object
was created using the object literal "{}" vs an Object constructor.
jQuery copied this hack I believe but for what utility I couldn't
guess. According to some bug reports it looks like its being used to
differentiate between native objects and JS Objects (attempting to at
least): http://forum.jquery.com/topic/improvement-to-isplainobject
 
G

Gordon

Hello everybody,

I have a problem with jQuery.

At moment of opening the page, he doesn't contain any button but the javascript
for the button is loaded.

When the user execute some function, I must add a button on the page.

I use the command :

$("#t1").html('<input type="button" name="bt_Save" id="bt_Save" value="Save"
/>');

The code function well. The button appear correctly. But when I clic on the
button, nothing happens. Such as no event does exist.

in the javascript, I write the following code (in the header of the page):

  jQuery(document).ready(function(){
    jQuery("#bt_Save").click(function(){
        alert('Hello');
    });
  });

Have you some ideas to resolve the problem?

I use the JQuery version : 1.4.2

Thank you in advance
Best regards

Andre

You can't attach an event to an object that doesn't exist yet. Either
attach the event to the object after you've created it with the .html
call, or use the .live method of doing events
 
A

Asen Bozhilov

RobG said:
| 12.6.4 The for-in Statement
| ...
| The mechanics of enumerating the properties ... is
| implementation dependent. The order of enumeration is
| defined by the object

So there is no reason to believe that every implementation will
enumerate own properties first and it can be demonstrated to be a
false assumption in IE 6 at least:

If the implementation does not enumerate own properties first, that is
not conformable implementation of ECMAScript. In 12.6.4 you can see:

| Enumerating the properties of an object includes enumerating
| properties of its prototype, and the prototype of the
| prototype, and so on, recursively; but a property of a prototype
| is not enumerated if it is “shadowed” because some
| previous object in the prototype chain has a property with the same
name.
 
S

Scott Sauyet

Asen said:
If the implementation does not enumerate own properties first, that is
not conformable implementation of ECMAScript. In 12.6.4 you can see:

| Enumerating the properties of an object includes enumerating
| properties of its prototype, and the prototype of the
| prototype, and so on, recursively; but a property of a prototype
| is not enumerated if it is “shadowed” because some
| previous object in the prototype chain has a property with the same
| name.

"Previous object in the prototype chain" certainly does not imply
"previous object in the enumeration."

-- Scott
 
A

Asen Bozhilov

Scott said:
Asen Bozhilov wrote:

"Previous object in the prototype chain" certainly does not imply
"previous object in the enumeration."

As I understand it:

var obj = {
x : true,
y : true
};

During evaluation of for-in there are no any rules for order of
enumerated properties of that object. For example for-in can enumerate
`y' follow by `x' property. But enumeration of objects in prototype
chain is defined by previous quotation. How you interpret the follow
sentence:

| Enumerating the properties of an object includes enumerating
| properties of its prototype, and the prototype of the
| prototype, and so on, recursively;

Abstractly I understand as:

function Enumerator(obj) {
if (obj == null) {
return;
}
while(HasEnumProperty(obj)) {
var next = GetNextEnumProperty(obj);
if (!HashMap[next])
{
EvaluateStatement();
HashMap[next] = true;
}
}
Enumerator(obj.PROTOTYPE);
}

And in my code `GetNextEnumProperty` is implementation depended by
ECMA-262 specification.
 
J

Jorge

As I understand it:

var obj = {
  x : true,
  y : true
};

Object.prototype.x= "X";

The spec says *what* should or shouldn't be returned, but not in which
order. It says that a for-in of `obj` should not return "x" a second
time when traversing Object.prototype, because Object.prototype.x is
being shadowed by obj.x.
 
R

RobG

RobG wrote: [...]
where - hasOwnProperty - is a global variable that is a reference to
Object.prototype.hasOwnProperty in Firefox but in IE 6 returns
undefined.

No, `hasOwnProperty` is an identifier in containing scope. It has the
value of `Object.prototype.hasOwnProperty`:

|  // Save a reference to some core methods
|  toString = Object.prototype.toString,
|  hasOwnProperty = Object.prototype.hasOwnProperty,

My error, those lines aren't indented and I missed the opening
(function... bit, didn't think they'd be *that* sloppy.
[...]

That code will reveal a quirk in Blackberry9000. BB9k creates, for the
activation object (AO), an Object object, and so for scope chain and
identifier resolution, the property will be resolved on the AO's
[[Prototype]], Object.prototype. It's a bad feature, but AFAICT it is
standards compliant with ECMA-262 edition 3.

Discussed here:http://groups.google.com/group/comp.lang.javascript/msg/1414bf1c85e0a...

Example:
<http://github.com/GarrettS/ape-javascript-library/blob/master/adhocte...>

Explanation:
<http://yura.thinkweb2.com/named-function-expressions/#activation-obje...>

[explanation of enumeration order]

I should have investigated that one. In fact I thought that that code
comment was wrong. I just was focusing on getting the code formatted and
counting `if` and `else` statements.
  Object.prototype.bar = 'bar';
  var obj = {};
  obj.foo = 'foo';
  for (var k in obj) {}
  alert(k);  // shows 'foo' in IE 6
                  // shows 'bar' in Firefox
so in IE, the inherited property was enumerated before the assigned
one, in Firefox it is enumerated after.

Result:
IE 6, 7, 8:
   b, a
Firefox 2, 3.6, Opera 10.5:
   a, b

Example code:
   function X(){this.a=1;}
   X.prototype={b:2});
   var x = new X;
   for(var prop in x)
     alert(prop);
The significance of all enumerable properties being own properties is,
presumably, that they were added by assigning them directly to the
object and therefore it hasn't inherited any from its [[prototype]].
That logic is only supported by observation in a small number of
browsers and is wrong in one of jQuery's supported set.

Three versions of IE. That counts as three browsers.

The result is not surprising. Relying on nonstandard behavior is risky.
Its crazy to check that in and not even test it though. Maybe a there
was a test error?

They could have checked the result of calling `hasOwnProperty` in the
body of the loop. They don't support Safari 2, I believe, so they could
get away with that. For Safari 2, they could either provide a fallback
or could at the very least, provide something that wont throw errors, e.g..:

var hasOwnProperty = ({}).hasOwnProperty || Function.prototype;

- and calling hasOwnProperty in Safari 2 wouldd result in the value
`undefined` being returned, instead of an error being thrown. Not a good
solution, but at least no errors in Safari 2.

Another solution for checking hasOwnProperty is to check, where
supported, the `__proto__`

more widely supported is - obj.propertyIsEnumerable - which doesn't go
down the [[prototype]] chain. However, it looks a bit weird doing:

for (var p in obj) {
if (obj.propertyIsEnumerable(p)) {
...

when the value of p should always be enumerable, but the test will
return false if p is on obj's [[prototype]] chain.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top