我有一个相当学术的问题,它并不特别适用于我正在做的任何事情,我真的很想知道答案!
假设我们在全局命名空间中有一个简单的对象定义,如下所示:
TestObject = function(){};
它的原型中添加了一个方法,可以将其实例化为新对象本身:
TestObject.prototype.AnotherObject = function() {};
实例化第一个对象:
var myObject = new TestObject();
现在我的问题是:
如何
myObject.myProperty = new myObject.AnotherObject();
不同于
myObject.myProperty = new TestObject.prototype.AnotherObject();
还是它们完全一样?
我看到的区别是:我可以使用第二种方法在 TestObject 上下文中实例化对象而不知道实例化对象本身的名称,即
TestObject.prototype.createAnObject = function() {
this.anotherProperty = new TestObject.prototype.AnotherObject();
}
最后:
使用原型方法实例化同名对象的含义是什么?为什么这会导致无限循环?(里面到底发生了什么……)
TestObject.prototype.AnotherObject = function () {
this.AnotherObject = new TestObject.prototype.AnotherObject();
};
myObject.AnotherObject();
然而这并不...
TestObject.AnotherObject = function() {};
TestObject.prototype.createAnObject = function() {
this.AnotherObject = new TestObject.prototype.AnotherObject();
};
myObject.createAnObject();
...
我非常渴望了解这里的对象之间的关系!谢谢!
我问这些问题的原因是因为我想在对象之间存在 1:1 关系的地方做出类似的事情:
ClientObject = function () {
this.objectname = "a client class";
}
ClientObject.prototype.loginUser = function(name) {
this.loggedin = true;
if (typeof this.User === 'undefined') {
this.User = new ClientObject.User(name);
}
}
ClientObject.User = function (name) {
this.username = name;
}
ClientObject.User.prototype.getProfile = function() {
return 'user profile';
}
var testClient = new ClientObject();
console.log('testClient.User = ' + (typeof testClient.User)); // should not exist
testClient.loginUser('Bob'); // should login 'bob'
console.log('testClient.User = ' + (typeof testClient.User)); // should exist now Bob is logged in
console.log(testClient.User.username); // should be bob
testClient.loginUser('Tom'); // should not do anything as User object already created
console.log(testClient.User.username); // bob still
console.log(testClient.User.getProfile()); // new functionality available
我只是不确定我是否在不知不觉中违反了任何最佳实践或约定。