3

firefox (v52.0), jquery

this works:

// example 1
$('html').find('body')

this works:

// example 2
var h
h=$('html')
h.find('body')

This doesn't work:

// example 3
var f
f=$('html').find
f('body')

I get

Error: Permission denied to access property "ownerDocument"

why?

but this works:

// example 4
var a
a = x => $('html').find(x)
a('body')
Ry-
  • 218,210
  • 55
  • 464
  • 476
Jasen
  • 11,837
  • 2
  • 30
  • 48

2 Answers2

3

Example 3 doesn't work because find is called on the global context when you assign it to f. If you use call and pass in a valid jQuery object as the context, the code works. Try this

var f = $('html').find;
console.log(f.call($('html'), 'body').length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Also, example 4 works because a can be translated to the following code, if written without an arrow function.

var a = function(x) {
  return $('html').find(x);
};

It's just example 1, but with a wrapper function in order to take a parameter

maazadeeb
  • 5,922
  • 2
  • 27
  • 40
  • that seems to work. but what does that error message mean? – Jasen Jul 28 '17 at 05:17
  • 1
    I actually get a different error message, _"this.pushStack is not a function"_. I know that this error is because the _this_ context is not a valid `jQuery` object. Maybe, your error is also something to do with the context being wrong. – maazadeeb Jul 28 '17 at 05:23
  • I think you answer is correct. javascript `this` is confusing me. – Jasen Jul 28 '17 at 05:32
  • Read [this](https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md#nothing-but-rules) for a good explanation. – maazadeeb Jul 28 '17 at 05:44
1

No, jQuery is not functional

By looking at jQuery core source code: https://github.com/jquery/jquery/blob/master/src/core.js#L51

You could see it hold state in this.

In f=$('html').find, the this of f is changed and no longer the this holding $('html') state

--

In this case, you are just proxy the method call. The this of find no change.

var a
a x => $('html').find(x)
a('body')
kkpoon
  • 1,939
  • 13
  • 23