简体   繁体   English

object 字面量 javascript 中的函数

[英]functions in object literal javascript

i'm a newbie starting to learn java-script..我是一个新手开始学习java脚本..

 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.类型错误:textchanger.callfun 不是 Object 的 function。

TextChanger is the function not a plain variable so below code works: TextChanger 是 function 不是普通变量,因此以下代码有效:

textchanger().callfun()

textchanger is a function, but It doesn't return any thing: I think you mean this: textchanger 是 function,但它不返回任何东西:我认为您的意思是:

 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();

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

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.看起来您正在尝试使用闭包,但要做到这一点,您需要从您最初调用的 function返回内部 function。 You can then assign that returned function to a variable, and then call that.然后,您可以将返回的 function 分配给一个变量,然后调用它。

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.) setTimeout用于显示如何使用不同的文本再次调用相同的 function,并获得不同的结果。)

 // 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM