javascript - "This" is returning [object Window], not the element - Stack Overflow

I have this simple code for debugging (there's more, but this is the stripped version):function ca

I have this simple code for debugging (there's more, but this is the stripped version):

function calc(container) {
    console.log(container);
    return 100;
};

$(".replace").text(calc(this));

The console is just returning the window, not the element. Why is this? Is there something that prevents jQuery/JavaScript from returning the element?

I have this simple code for debugging (there's more, but this is the stripped version):

function calc(container) {
    console.log(container);
    return 100;
};

$(".replace").text(calc(this));

The console is just returning the window, not the element. Why is this? Is there something that prevents jQuery/JavaScript from returning the element?

Share Improve this question asked Nov 6, 2013 at 2:34 IanIan 6,1746 gold badges45 silver badges76 bronze badges 1
  • 2 Yes, this is window in that scope. – elclanrs Commented Nov 6, 2013 at 2:36
Add a ment  | 

5 Answers 5

Reset to default 2

Because the calc method is not invoked within the element's context, you need to use something like

$(".replace").text(function(){
    return calc(this)
});

in this case the calc method is invoked within a callback method where this refers to the current element.

Demo: Fiddle

this here refers to the window object

$(".replace").text(calc(this));

you should use

$(".replace").text(function(){
    return calc(this); // here this refers to the current element with class replace
});

Read this keyword

In the global context, this is window.

> this === window
true

What you want is probably something like this:

var $replace = $(".replace");
$replace.text(calc($replace));

Just another option, since you are looking for the element just use your function reference itself as the argument of text.

function calc() {
    console.log(this);
    return 100;
};

$(".replace").text(calc);

That's right.

Because when you call that function the current scope is window.

If you want to use the element, use function parameter instead.

Refer jQuery set text

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745246291a4618426.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信