简体   繁体   English

Javascript无法在onclick事件中访问函数内的全局对象

[英]Javascript Unable to access global object inside a function in an onclick event

We have the usual example code where everything works.我们有通常的示例代码,一切正常。

( myFunction gets triggered on an onclick event.) myFunction在 onclick 事件上触发。)

"use strict";
console.clear();

const obj = {
    name: "falana",
    count: 0
};

function myFunction() {
    obj.count++;
    console.log(obj.count);
    console.log(obj.name);
    console.log(obj);
}

---Output--- - -输出 - -

1
"falana"
// [object Object] 
{
  "name": "falana",
  "count": 1
}

From this example, we can access a global object obj inside another function (in this case, myFunction ) without any ReferenceError .在这个例子中,我们可以在没有任何ReferenceError情况下访问另一个函数(在本例中为myFunction )中的全局对象obj

I was trying to create a single page Twitter clone (only DOM manipulation) and kept getting this error.我试图创建一个单页Twitter 克隆(仅限 DOM 操作)并不断收到此错误。 Uncaught ReferenceError: Cannot access 'userData' before initialization at postMessage

---Javascript that's causing error--- ---导致错误的Javascript---

window.onload = function() {
  console.clear();
}

const userData = {
  username: 'Chinmay Ghule',
  userhandle: generateUserhandle(this.username),
  userPostCount: 0
};

function generateUserhandle(userData) {
  const usernameArr = userData.username.split(" ");
  usernameArr.forEach(element => {
    element.toLowerCase();
  });

  return "@" + usernameArr.join("");
}

// posts message entered in #message-text to
// message-output-container.
function postMessage() {

  console.log(userData);

  // get message from #message-text.
  const message = document.getElementById('message-text').value;
  console.log(`message: ${message}`);

  // check for length.
  console.log(`message length: ${message.length}`);
  if (message.length === 0) {
    return;
  }

  // create new div.
  const card = document.createElement('div');
  const userInfo = document.createElement('div');
  const userMessage = document.createElement('div');

  const usernameSpan = document.createElement('span');
  const userhandleSpan = document.createElement('span');
  const beforeTimeDotSpan = document.createElement('span');
  const timeSpan = document.createElement('span');

  usernameSpan.classList.add('username');
  userhandleSpan.classList.add('userhandle');
  beforeTimeDotSpan.classList.add('before-time-dot');
  timeSpan.classList.add('time');

  userInfo.appendChild(usernameSpan);
  userInfo.appendChild(userhandleSpan);
  userInfo.appendChild(beforeTimeDotSpan);
  userInfo.appendChild(timeSpan);

  console.log(`userInfo : ${userInfo}`);

  userInfo.classList.add('user-info');
  userMessage.classList.add('output-message');

  card.appendChild(userInfo);
  card.appendChild(userMessage);

  console.log(`card : ${card}`);

  card.classList.add('output-message');

  userMessage.innerText = message;

  // check for number of posts.
  if (userData.userPostCount === 0) {
    let noMessageDiv = document.getElementById("no-message-display");

    noMessageDiv.remove();
  }

  // append new div.
  const messageOutputContainer = document.getElementById('message-output-container');

  messageOutputContainer.appendChild(card);

  // increment userPostCount.
  userData.userPostCount++;
}

Why am i getting this ReferenceError in this case, while it didn't in our first example code?为什么在这种情况下我会收到这个ReferenceError ,而在我们的第一个示例代码中却没有?

Your code had quite some issues...你的代码有很多问题......

The biggest change here was getting rid of generateUserhandle entirely and making it with a getter .这里最大的变化是完全摆脱了generateUserhandle并使用了getter

  get userhandle() {
    return this.username.toLowerCase()
  },

Working demo工作演示

 window.onload = function() { console.clear(); } const userData = { username: 'Chinmay Ghule', get userhandle() { return this.username.toLowerCase() }, userPostCount: 0 }; // posts message entered in #message-text to // message-output-container. function postMessage() { console.log(userData); // get message from #message-text. const message = document.getElementById('message-text').value; console.log(`message: ${message}`); // check for length. console.log(`message length: ${message.length}`); if (message.length === 0) { return; } // create new div. const card = document.createElement('div'); const userInfo = document.createElement('div'); const userMessage = document.createElement('div'); const usernameSpan = document.createElement('span'); const userhandleSpan = document.createElement('span'); const beforeTimeDotSpan = document.createElement('span'); const timeSpan = document.createElement('span'); usernameSpan.classList.add('username'); userhandleSpan.classList.add('userhandle'); beforeTimeDotSpan.classList.add('before-time-dot'); timeSpan.classList.add('time'); userInfo.appendChild(usernameSpan); userInfo.appendChild(userhandleSpan); userInfo.appendChild(beforeTimeDotSpan); userInfo.appendChild(timeSpan); console.log(`userInfo : ${userInfo}`); userInfo.classList.add('user-info'); userMessage.classList.add('output-message'); card.appendChild(userInfo); card.appendChild(userMessage); console.log(`card : ${card}`); card.classList.add('output-message'); userMessage.innerText = message; // check for number of posts. if (userData.userPostCount === 0) { let noMessageDiv = document.getElementById("no-message-display"); noMessageDiv.remove(); } // append new div. const messageOutputContainer = document.getElementById('message-output-container'); messageOutputContainer.appendChild(card); // increment userPostCount. userData.userPostCount++; }
 *, *::before, *::after { box-sizing: border-box; } body { margin: 0px; padding: 0px; font-family: Arial, Helvetica, sans-serif; } #container { /*background-color: lightskyblue;*/ margin: 2.5rem 25%; } #user-info { /*background-color: orange;*/ padding-bottom: 0.5rem; } .username { font-weight: bold; } .userhandle, .before-time-dot, .time { opacity: 0.75; } #message-text { width: 100%; margin-bottom: 0.5rem; font-size: 18px; padding: 0.5rem; resize: none; border-radius: 0.5rem; outline: 1px solid lightgray; } #message-button { float: right; padding: 0.375rem 1.5rem; font-weight: bold; font-size: 18px; border-radius: 1rem; } #message-button:hover { background-color: lightgray; } #message-input-container { background-color: lightskyblue; padding: 1rem; border-radius: 0.5rem; } #message-input-container::after { content: ""; clear: both; display: table; } #message-output-container { /*background-color: lightskyblue;*/ margin-top: 30px; border-top: 3px solid black; } #no-message-display { text-align: center; padding: 0.5rem; } .output-message { padding: 0.5rem; font-size: 18px; border-bottom: 1px solid lightgray; }
 <div id="container"> <div id="message-input-container"> <textarea id="message-text" rows="5" placeholder="Type your message here..." contenteditable="" value=""></textarea> <input id="message-button" type="button" value="Post" onclick="postMessage();" /> </div> <div id="message-output-container"> <div id="no-message-display"> <span>No messages yet!</span> </div> </div> </div>

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

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