Javascript:在该对象中调用对象方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10918228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:33:38  来源:igfitidea点击:

Javascript: Calling object methods within that object

javascriptoopmethods

提问by Marcus Hughes

What is the best design pattern for achieving the following (which doesn't work)?

实现以下目标的最佳设计模式是什么(不起作用)?

var obj = (function() {

  // code defining private variables and methods

  var _obj = {
    property: value,
    method1: function() {
      // do stuff
    },
    method2: function() {
      // use property
      var prop = _obj.property; // obviously doesn't work
      // call method1
      obj.method1(); // "obj" not finished being defined yet!
    }
  };

  // obviously now I could do...
  var prop = _obj.property;

  return _obj;

})();

// and I could now do...
obj.method1();

A variation which I think should work is

我认为应该起作用的变体是

var obj = (function() {

  var property = value,
      method1 = function() {
        // do stuff
      },
      method2 = function() {
        // use property
        var prop = property;
        // call method1
        method1();
      },
      _obj = {
        property: property,
        method1: method1,
        method2: method2
      };

  return _obj;

})();

Similarly, how does it work for objects meant to be created with the newoperator? Within the constructor function itself you can write this.method(). But what if you want to keep the constructor small, only defining those things which will likely be customized upon creation, and then defining the rest in the prototype? (This seems to be the common pattern.) Can the properties / methods within the prototype interact in any way?

类似地,它如何处理要由new操作符创建的对象?在构造函数本身中,您可以编写this.method(). 但是,如果您想让构造函数保持较小,只定义那些可能会在创建时自定义的内容,然后在原型中定义其余部分,该怎么办?(这似乎是常见的模式。)原型中的属性/方法可以以任何方式交互吗?

var MyObj = function(name) {
  this.name = name;
};

var obj = new MyObj('Bob');

MyObj.prototype = {
  called_often: function() {
    // lots more code than just the following
    return document.getElementById('someID').value;
  },

  global_default: 'value', // can be changed, so need to pull value when run

  does_stuff: function(value) {
    var str = global_default + value, // can't access global_default on its own
        input = MyObj.called_often(), // doesn't work; MyObj.prototype.called_often() DOES
        name = this.name; // 'this' used in the prototype doesn't work
                          // even within a created object
    return name + input + str;
  }
};

I'm sure there's better ways to achieve my result whenever I run into this problem. This code isn't situation specific and just illustrates the general problem. So you won't be able to give me an alternative for those specific situations I run into. But maybe you can help my overall thinking.

我相信每当我遇到这个问题时,都有更好的方法来实现我的结果。此代码不是特定于情况的,只是说明了一般问题。因此,对于我遇到的那些特定情况,您将无法为我提供替代方案。但也许你可以帮助我的整体思考。

回答by Pointy

Well, from your first example:

好吧,从你的第一个例子来看:

var _obj = {
    property: value,
    method1: function() {
      // do stuff
    },
    method2: function() {
      // use property
      var prop = this.property; 
      // call method1
      this.method1(); 
    }
  };

That's what the thisvalue is for.

这就是this价值所在。

Now, what you cannot do is refer to a property of an "under construction" object from elsewhere in the object literal syntax. (It's hard to give an example because it's just not syntactically possible.) In cases where you want to do that, you do need one or more separate assignment statements.

现在,您不能做的是从对象字面量语法的其他地方引用“正在构建”对象的属性。(很难举一个例子,因为它在语法上是不可能的。)如果你想这样做,你确实需要一个或多个单独的赋值语句。

回答by Parth Thakkar

Guess what? You are making simple stuff complex. Pointy's answer is good, but the prototype way is better for several reasons. That's why I am describing (rather, making corrections in) the last method. Check this fiddle.

你猜怎么着?你正在把简单的东西复杂化。Pointy 的回答很好,但由于几个原因,原型方式更好。这就是为什么我要描述(而是更正)最后一种方法。检查这个小提琴

var MyObj = function(name) {
  this.name = name;
};

MyObj.prototype = {
  called_often: function() {
    // lots more code than just the following
    return 'VALUE'; //document.getElementById('someID').value;
  },

  global_default: 'value', // can be changed, so need to pull value when run

  does_stuff: function(value) {
    var str = this.global_default + value, // can't access global_default on its own
        input = this.called_often(), // doesn't work; MyObj.prototype.called_often() DOES
        name = this.name; // 'this' used in the prototype doesn't work
                          // even within a created object
    return name + input + str;
  }
};

var obj = new MyObj('Bob');