我在 OA 上被问到以下问题。我没弄清楚,我想知道这个问题的答案。
我被要求控制台感谢您登录 Dan
:
var Wrap = (function(){
function User(name){
this.name = name;
}
var d = function(){
console.log('1');
return "Thank you for Logging in" + this.name;
};
User.prototype.thankForLoggingln = d;
return User;
})();
我发现Wrap
返回User,这使得Wrap
等于User
。如果我执行 Wrap('Dan')
,this.name
将更改为 Dan
。
问题是,我无法访问 thankForLoggingln
。我尝试过 Wrap.()thankForLoggingln()
之类的东西,但出现了引用错误。有什么想法吗?
最佳答案
您的理解
I figured that out that Wrap returns User, which make Wrap equals to User
是正确的。但是,当您说 Wrap('Dan')
时,在本例中 this
将引用 Global 对象。如果您在浏览器上运行它,那么您可以通过 window.name
访问您的 name 变量。您必须使用 new
关键字调用该函数,以便创建一个新对象,并且 this
将引用新创建的对象和 User
将是它的构造函数。在这种情况下,它将有权访问 thankForLoggingln
函数。
所以正确的做法是
var user = new Wrap('Dan');
user.thankForLoggingln();
欲了解更多信息,请阅读constructor和 You Don't Know JS
关于javascript - 将一个函数原型(prototype)化为另一个函数 JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49144140/