javascript - 匿名函数和未定义成员值的问题

标签 javascript

我在这里问了一个问题: Extending javascript literal object

这个问题已经解决了,因为我忘了返回。现在我没有忘记返回,我又得到了未定义,为什么?

<script>
    var secretAgent = (function(){
      var person = {},
          firstName = "James",
          lastName = "Bond";
      person.WhoAreYou = function() {
        alert("My name is " + this.lastName + ", " + this.firstName + " " + this.lastName);
      };
      return person;
    })();
  </script>

  <script>
    secretAgent.WhoAreYou();
  </script>

更新:为什么我的不起作用,而我认为我做了与下面有效的相同的事情:

http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/

//Revealing Module Pattern (Public & Private)
var skillet = (function() {
    var pub = {},
        //Private property
        amountOfGrease = "1 Cup";

    //Public property   
    pub.ingredient = "Bacon Strips";

    //Public method
    pub.fry = function() {
        console.log( "Frying " + pub.ingredient );
    };

    //Private method
    function privateWay() {
        //Do something...
    }

    //Return just the public parts
    return pub;
}());

//Public Properties
console.log( skillet.ingredient ); //Bacon Strips

//Public Methods
skillet.fry();

//Adding a public property to a Module
skillet.quantity = 12;
console.log( skillet.quantity ); //12

//Adding a public method to a Module
skillet.toString = function() {
    console.log( skillet.quantity + " " +
                 skillet.ingredient + " & " +
                 amountOfGrease + " of Grease" );
};

try {
    //Would have been successful,
    //but can't access private variable
    skillet.toString();
} catch( e ) {
    console.log( e.message ); //amountOfGrease is not defined
}

最佳答案

您需要在文字本身上声明这些属性(而不是单独的不相关变量),如下所示:

var secretAgent = (function(){
  var person = { firstName: "James", lastName: "Bond" };
  person.WhoAreYou = function() {
    alert("My name is " + this.lastName + ", " + this.firstName + " " + this.lastName);
  };
  return person;
})();

You can test it out here .

关于javascript - 匿名函数和未定义成员值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4257779/

相关文章:

javascript - 在移动和平板设备上更改 PHP 循环内的 Bootstrap 列顺序

javascript - 调用 addEventListener 数百次

javascript - puppeteer 中页面选择器的奇怪行为

javascript - ajax 使用 json、nodejs 和 webpack 返回 401

javascript - 当我尝试在 React 中打印时,为什么 props 不显示

javascript - JQuery Ajax 获取自定义

javascript - 当某个类调用时,我如何设置隐藏的正文溢出

javascript - 在liferay中为aui窗体添加动态元素

javascript - javascript是否使用弹性赛道算法进行处理

javascript - 如何将 svg 放在 div 中