如何在参数化函数中使用对象属性?

我一直在研究一个项目中的对话框,并将它变成一个对象构造函数。


function createDialog(title, noClicked = function(){}, yesClicked = function(){}) {

  this.dialog = document.getElementsByClassName("dialog")[0];

  this.dialogTitle = this.dialog.getElementsByTagName("h1")[0];

  this.No = this.dialog.getElementsByTagName("button")[0];

  this.Yes = this.dialog.getElementsByTagName("button")[1];


  var dialog = document.getElementsByClassName("dialog")[0];

  this.dialogTitle.innerHTML = title;

  document.getElementsByClassName("dialogCon")[0].style.display = "flex";


  noClicked();


  yesClicked();

}

<div class="dialogCon">

      <div class="dialog">

        <h1></h1>

        <button type="button">No</button>

        <button type="button">Yes</button>

      </div>

    </div>


问题是,当我想访问“this.no”或“this.yes”时,我不断收到Cannot read property 'No' of undefined。当我使用以下代码时发生了这种情况:


var d = new createDialog("Sample dialog. Exit?", function() {

  console.log(d.No);

}, function() {

  console.log(d.Yes);

});


我需要使用 d.No 关闭对话框。还有其他方法吗?或者至少是一个修复。

我知道我可以从构造函数本身关闭对话框,但我也想让它也可以做其他事情(比如检测用户是否选择是或否)。


婷婷同学_
浏览 122回答 2
2回答

catspeake

您在构造函数中立即调用noClicked()和 yesClicked()。我想你会想在点击No和Yes时给他们打电话。您需要将这些功能添加到按钮的事件侦听器中。试试下面的片段。function createDialog(title, noClicked = function(){}, yesClicked = function(){}) {&nbsp; this.dialog = document.getElementsByClassName("dialog")[0];&nbsp; this.dialogTitle = this.dialog.getElementsByTagName("h1")[0];&nbsp; this.No = this.dialog.getElementsByTagName("button")[0];&nbsp; this.Yes = this.dialog.getElementsByTagName("button")[1];&nbsp; var dialog = document.getElementsByClassName("dialog")[0];&nbsp; this.dialogTitle.innerHTML = title;&nbsp; document.getElementsByClassName("dialogCon")[0].style.display = "flex";&nbsp; this.No.addEventListener('click',noClicked);&nbsp; this.Yes.addEventListener('click',yesClicked);}&nbsp;&nbsp;&nbsp;var d = new createDialog("Sample dialog. Exit?", function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(d.No);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(d.Yes);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;});<div class="dialogCon">&nbsp; &nbsp; &nbsp; <div class="dialog">&nbsp; &nbsp; &nbsp; &nbsp; <h1></h1>&nbsp; &nbsp; &nbsp; &nbsp; <button type="button">No</button>&nbsp; &nbsp; &nbsp; &nbsp; <button type="button">Yes</button>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </div>

吃鸡游戏

因为你现在有了构造函数,回调会立即被调用,只有在它们被调用之后构造函数才会返回。对此有两点评论:由于调用回调时构造函数尚未返回,因此变量d尚未收到值。所以d在回调中将是undefined。这是不现实的,因为在实践中您只想调用其中一个回调,并且仅在用户单击按钮时调用。那个时候d会被定义。您仍然可以通过传递对构造对象的显式引用来解决它。例如,您可以将其作为this对象传递:改变:noClicked();...到:noClicked.call(this);然后在您的回调中,更改:console.log(d.No);...到:console.log(this.No);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript