Home > Back-end >  functions in object literal javascript
functions in object literal javascript

Time:09-18

i'm a newbie starting to learn java-script..

const textchanger = function () {
let text = "text that has been changed now"
const picktext = function () {
    let element = document.querySelector("h1")
    element.textContent = text

    return {
        callfun: function () {
            picktext();
            console.log(text);

        }

    }

}
}

textchanger.fun()
 <h1> Getting started </h1>

i'm trying to change the text inside

<h1>Getting started</h1>

but getting the error..

TypeError: textchanger.callfun is not a function at Object.

CodePudding user response:

TextChanger is the function not a plain variable so below code works:

textchanger().callfun()

CodePudding user response:

textchanger is a function, but It doesn't return any thing! I think you mean this:

const textchanger = function () {
  let text = "text that has been changed now";
  const picktext = function () {
    let element = document.querySelector("h1");
    element.textContent = text;

    return {
      callfun: function () {
        picktext();
        console.log(text);

      }
    }

  }
  return picktext(); // <==== put this line
}

textchanger().callfun();

CodePudding user response:

const textchanger = function () {
let text = "text that has been changed now";
const picktext = function () {
let element = document.querySelector("h1");
element.textContent = text;
  return {
    callfun: function () {
    picktext();
    console.log(text);
   },
  };
};
  return picktext(); ==>return picktext() function 
 };

textchanger(); ==> by calling this the text will be changed

CodePudding user response:

I looks like you're experimenting with closures but to do that you need to return the inner function from the function you initially call. You can then assign that returned function to a variable, and then call that.

Here's an example that shows how this works. (The setTimeout is there to show how the same function can be called again with different text, and get a different result.)

// Accept an element, and return a new function
// that accepts some text. `element` will be returned
// along with the inner function so it can be used
function textChanger(element) {
  return function (text) {
    element.textContent = text;
  }
}

// Cache the element
const element = document.querySelector('h1');

// Call `textChanger` with the element as its
// argument, and assign the returned function to
// a variable
const changeText = textChanger(element);    

// Call that function with some text
changeText('First text!');

// Call the same function with some different text
setTimeout(changeText, 2000, 'Second text!');
<h1>Getting started</h1>

  • Related