例如,假设我在浏览器的全局窗口中定义了以下构造函数。
function AccessProperty() {
this.myName = "Chris";
}
现在我像这样执行这个函数:
new AccessProperty();
现在,根据我如何使用new关键字执行上面的函数,我如何才能访问this.myName
属性,而不添加如下内容:
var acccess = new AccessProperty();
发布于 2018-09-25 07:33:44
真的不清楚你的最终目标是什么。this
是一个上下文引用,它根据函数的上下文而变化。当您使用new
时,this
引用js系统为您创建的对象,并返回给调用者。如果没有new
,这将是全局窗口,如果您只调用该函数。
您可以使用像call()
这样的函数显式地告诉函数this
是什么
function AccessProperty() {
this.myName = "Chris";
}
let someObject = {}
AccessProperty.call(someObject) // this will be someObject
console.log(someObject.myName) // to which the function adds myName.
但是,当您可以只使用new
并获得一个具有myName
属性的对象时,这似乎是一种很难做的事情。
为了演示this
的动态特性,请考虑下面的代码:
function AccessProperty() {
this.myName = "Chris";
}
let o = {
set: AccessProperty,
talk() {console.log(this.myName)}
}
// because of the way it's called `this` in
// the function AccessProperty will be
// the object o
o.set()
o.talk()
console.log(o) // o now has a myName property
这种行为在某些情况下非常有用,如果你不想要这种行为,你可以使用this
,你可以只定义变量。
发布于 2018-09-25 07:14:11
如果你不是在严格模式下,你可以这样做
function AccessProperty(){
this.name="ram"
}
function parent(){
AccessProperty.bind(this)
AccessProperty()
console.log(this.name)
}
parent()
这里我们将AccessProperty函数的作用域绑定到父函数的作用域。完成此操作后,名称将位于父函数的作用域中
https://stackoverflow.com/questions/52488444
复制相似问题