【发布时间】:2023-12-18 02:17:01
【问题描述】:
如果我通过new constructor() 调用创建一个对象,如下所示:
function constructor(){
function privateFn(){
console.log('this is private');
}
this.publicFn = function(){
console.log('this is public');
}
function doSomething(){
privateFn();
publicFn();
}
console.log(this.publicFn ? "exists" : "does not exist"); // logs exists
doSomething(); //throws an error -> publicFn() is not this.publicFn().
}
new constructor();
所以问题是,有没有办法在没有this. 部分的情况下使它可以访问?
即使没有 this.,我的 IDE(netbeans)似乎也能识别它,尽管这并不一定意味着什么,但它让我想知道,是否有可能以某种方式引用 publicFn() 作为函数,而不是作为目的?也许构造不同?
编辑: 目标是使用new 构造函数创建一个同时具有私有和公共方法的对象,但同时允许构造函数本身以及所有对象的方法调用没有 this. 前缀的公共方法。
BEKIM BACAJ 特别编辑
专门为您更新了此部分,只是为了向您展示我的意思。
这不是在欺骗我的 console.log,对 doSomething 的调用或在对象确实创建后出现的任何其他方法。虽然它仍然无法访问,现在我已经看到了为什么的答案,它是有道理的。私有方法的上下文this 不一样,或者构造函数中的函数将this 设置为窗口,因此它们的上下文this 与它们尝试调用的公共方法不同. Phylogenesis 建议的模式正是我所寻找的,并且符合需求。
function constructor(){
function privateFn(){
console.log('Call to privateFN succesful');
console.log('------------------------------------------------------------------------------------');
}
function doSomething(){
console.log('Executing: doSomething;');
//I want to be able to access both private and public methods here (which i can)
//I want to be able to access them the same way (which I cannot).
privateFn(); //works
publicFn(); //error
//Read NOTE1 below.
}
this.callDoSomething = function(){
console.log('Call to callDoSomething succesful');
console.log('------------------------------------------------------------------------------------');
//made just so that you can access doSomething from the outside to test.
doSomething();
};
this.publicFn = function(){
console.log('Call to publicFN succesful');
console.log('------------------------------------------------------------------------------------');
};
//.... many more methods (we are talking hundreds)
//.... some of them are public, some are private
//.... some are resutls of calling functions that return functions from other files (collaborative work),
//.... these might be public or private, which we achive like so:
//.... var externalModule = extrenalModuleInitializer(this);
//.... as you can imagine this externalModuleInitializer function can either:
//.... A) PRIVATE: return a function, making this externalModule variable a private method
//.... B) PUBLIC: do stuff with the `this` object that was passed, adding public methods to it
//.... So since I do not know if certain parts of this object will be private or public, i need
//.... a way to access them in the same way in order to make the coding easier.
}
console.clear();
var a = new constructor();
a.publicFn();
a.callDoSomething();
【问题讨论】:
-
你的方法和代码本身都有问题
-
@BekimBacaj 然后解释一下什么是正确的方法
-
目前还不清楚你在使用 new fn 时首先要做什么 - 没有这样的构造函数,而不是你调用的函数调用了一个还不存在的函数。
-
构造函数中没有
this的方法不能公开 -
为什么要避免使用
this?
标签: javascript object this