从设置为原型的对象调用属性

Calling property from an object set to prototype

本文关键字:对象 调用 属性 原型 设置      更新时间:2023-09-26
var Foo = function() {
    this.message = "Hi";
}
Foo.prototype = {
    say: {
        hi: function() {
            console.log(this.message);
        }
    }
}

[编辑]我知道hi((中的"这个"指的是说,有什么方法可以实现这一点吗?

var he = new Foo();
he.say.hi(); //"Hi" to console

您可以像这样访问。

var Foo = function(){
  this.par = 3;
  this.sub = new(function(t){ //using virtual function to create sub object and pass parent object via 't'
    this.p = t;
    this.subFunction = function(){
      alert(this.p.par);
    }
  })(this);
}
var myObj = new Foo();
myObj.sub.subFunction() // will popup 3;
myObj.par = 5;
myObj.sub.subFunction()

您所需要的只是像这样绑定 hi 函数:

var Foo = function() {
    this.message = "Hi";
    this.say.hi = this.say.hi.bind(this);
}
Foo.prototype = {
    say: {
    hi: function() {
        console.log(this.message);
        }
    }    
}
var he = new Foo();
he.say.hi();