Javascript 原型构造函数调用

Javascript 原型构造函数调用,javascript,Javascript,不使用调用方法,是否可以使用以下方法,例如: var A = function(height,weight) { this.height = height; this.weight = weight; }; var a = new A("6ft","500lbs"); A.prototype.foo = { setup: function() { this.height.set(); this.weight(); },

不使用调用方法,是否可以使用以下方法,例如:

var A = function(height,weight) {
    this.height = height;
    this.weight = weight;
};

var a = new A("6ft","500lbs");

A.prototype.foo = {
    setup: function() {
        this.height.set();
        this.weight();
    },

    height: {
        set: function() {
            var constr = a;
            var self = this;

            console.log(constr);
            console.log(self);
        }
    },

    weight: function() {
        var constr = a;
        var self = this;

        (function() {
            console.log(constr);
        })();
    }
};

a.foo.setup();
欢迎提出任何建议


干杯

你可以这么做,但真是一团糟<代码>高度和
重量
有两种不同的含义;
A
的所有实例都将引用该首字母
A
。你想达到什么目的

编辑:

使用原型的问题在于,创建原型时,没有特定于实例的功能上下文(很明显,原型只创建一次,通常在类的任何实例之前创建。没有上下文,就没有地方存放实例的私有变量。我更喜欢在构造时创建方法:

var A = function(height, weight) {
    this.height = function() { return height; };
    this.weight = function() { return weight; };
};
使用函数创建原型本身为所有实例创建公共(私有、静态)上下文。您甚至可以混合使用以下概念:

var A = function(height, weight) {
    this.__init__(height, weight);
};

A.prototype.__init__ = (function() {
   // any variables declared here are private and static
   var number_of_instances = 0;
   return function(height, weight) {
      // any variables declared here are private and NOT static

      // as always, anything added to this are public and not static
      this.getNumberOfInstances = function() {
          return number_of_instances;
      };

      this.height = function() { return height; };
      this.weight = function() { return weight; };
      number_of_instances++;
   };
})();

我对过度编写整个原型并不感到兴奋,这意味着您无法将A更改为从另一个类继承。

我正在尝试实现在需要时调用构造函数属性的功能。此外,我希望能够拥有公共/私有作用域。前面提到的代码块更像是一个压力测试。谢谢,Y我们的示例运行得很好!我还有两个问题:-关于var a=new a()的位置;首选位置在哪里,例如:在构造函数函数之后,或在文件中的较低位置?另外,从pastie中的示例来看,这一组中哪一个更好?通常,代码定义类与定义相关类的代码一起保存,以便形成一个逻辑模块或库s、 一个实例被实例化——不管它需要在什么地方,它通常离得很远,通常在不同的文件中。pastie中的例子都有点奇怪,以微妙的不同方式。我认为你应该先设计一个漂亮整洁的API,然后编写代码来匹配它。顺便说一句,有点StackOverflow礼仪:如果你喜欢我的答案,sta你想实现什么?当我需要属性时,不使用call/apply方法从构造函数继承属性的能力。