0

UPDATE: .call function works, thanks for the quick replies :) Tested the other solution suggested too and

So I have this code, function setAttribute which takes four inputs and then applies them using this. The long code where it does

this.setAttribute("data-index-all", 1); works, but when I made it into a function it doesn't. I'm pretty sure that the problem is with "this" in a function. If someone could point out what's wrong I'd be very thankful.

function setAttribute(a, b, c, d){
this.setAttribute("data-index-all", a);
this.setAttribute("data-index-uleval", b);
this.setAttribute("data-index-vasakul", c);
this.setAttribute("data-index-paremal", d);
}    

if (!flipped) {
            setAttribute(1, 0, 1, 0);
        }else{
            setAttribute(0, 1, 0, 1);
        }


if (!flipped) {
                    this.setAttribute("data-index-all", 1);
                    this.setAttribute("data-index-uleval", 0);
                    this.setAttribute("data-index-vasakul", 1);
                    this.setAttribute("data-index-paremal", 0);
                } else {
                    this.setAttribute("data-index-all", 0);
                    this.setAttribute("data-index-uleval", 1);
                    this.setAttribute("data-index-vasakul", 0);
                    this.setAttribute("data-index-paremal", 1);
                }
1
  • 1
    javascript already has setAttribute so define another function name... Commented Mar 31, 2015 at 8:19

2 Answers 2

2

When you call a function without a context, this inside the function will refer to the global object(window).

You can use .call() to pass a custom context

function setAttribute(a, b, c, d) {
    this.setAttribute("data-index-all", a);
    this.setAttribute("data-index-uleval", b);
    this.setAttribute("data-index-vasakul", c);
    this.setAttribute("data-index-paremal", d);
}

if (!flipped) {
    setAttribute.call(this, 1, 0, 1, 0);
} else {
    setAttribute.call(this, 0, 1, 0, 1);
}

But in your scenario using @codehx answer will be best

Sign up to request clarification or add additional context in comments.

Comments

2

try passing the element to which this refers to as the function argument.

function setAttribute(element, a, b, c, d){
  element.setAttribute("data-index-all", a);
  element.setAttribute("data-index-uleval", b);
  element.setAttribute("data-index-vasakul", c);
  element.setAttribute("data-index-paremal", d);
}   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.