![](/img/trans.png)
[英]When I console.log type of my function which returns an object it gives undefined. I don't understand why
[英]Why when I do a console.log is my object within a function returned as 'undefined'? (Learning about creation phase, execution phase)
我試圖了解執行上下文,創建階段和執行階段。
我想知道,有人可以幫我理解為什么嗎,
console.log(thisFunction.ojbect1);
返回-'undefined'。
我本來以為,在創建階段之后,當變量被分配為“未定義”時,執行階段就會運行,然后在該階段將對象填充到變量中。
那么,為什么我要為“ object1”而不是整個對象獲取“ undefined”?
非常感謝。 下面的代碼。
var thisFunction = function(){
var object1 = {
firstname: 'Mark',
printName: function(){
console.log(this.firstname);
}
};
object1.printName();
};
thisFunction();
console.log(thisFunction.object1);
“ Object1”不是“ thisFunction”的屬性,因此不能調用它。 “ Object1”是在“ thisFunction”的范圍內創建的變量。
您只能訪問父范圍的變量。
如果您想了解更多有關功能范圍的信息,請閱讀以下有趣的文章。
這與您一樣工作,除了:
var thisFunction = function(){
this.object1 = {
firstname: 'Mark',
printName: function(){
console.log(this.firstname);
}
};
this.object1.printName();
};
var tf = new thisFunction();
console.log(tf.object1);
使用typeof
可以幫助您更好地了解對象和函數之間的區別:
console.log(typeof thisFunction);
console.log(typeof tf);
console.log(typeof tf.object1);
console.log(typeof tf.object1.firstname);
輸出:
功能
賓語
賓語
串
在Plunker中查看此示例
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.