(想直接看题目的话可以移到最後一个标题!)
在准备回答问题前,先复习几个观念:
→ Constructor建构子,用途是能制作大量相似的 object ( array, function...都是object)。
通常使用的形式为:
范例:
function Person(name, age, country){ // 字首大写
console.log(this); // 这里的this 会指向一个 empty object "Person {}"
this.name = name,
this.age = age,
this.country = country
}
let Tina = new Person("Tina", 22, "Taiwanese"); // 使用 "new" keyword
console.log(Tina); // Person {name: "Tina", age: 22, country: "Taiwanese"}
范例执行的动作:
console.log(this);
Tina
本身,也就是创造了一个empty object "Person {}"。this.name = name
let Tina = new Person("Tina", 22, "Taiwanese");
console.log(Tina);
( 注意! console.log(this);
的"Person {}"展开来可能还是会看到里面不是空的,还是会有内容。
这是因为物件传参考的特性,所以之後被定义的属性会同时被看到,这里可以大概知道就好。 )
那如果没有new会发生什麽事呢? 我们可以试试看:
function Person(name, age, country){
console.log(this); // output: Window {0: global, window: Window, …}
this.name = name,
this.age = age,
this.country = country
}
let Tina = Person("Tina", 22, "Taiwanese");
console.log(Tina); // output: undefined
console.log(this);
的this,会变成指向浏览器的Global object Window
。
然後在Window
里找不到定义属性的方法,所以Tina
就变成了undefined
(被消失
所以没有new就不会创造empty object,也会影响this的指向,
然後new不出object你的建构子就白搭了。
Constructor Function可以定义属性,也可以定义方法(methods)。
我们可以看到下面的例子:
function Person(name, age, country){
this.name = name,
this.age = age,
this.country = country,
this.sayHi = function(){
console.log(this.name + " says Hi."); // 这里的this会指向Person {}
}
}
let Tina = new Person("Tina", 22, "Taiwanese");
console.log(Tina); // Person {name: "Tina", age: 22, country: "Taiwanese", sayHi: ƒ}
Tina.sayHi(); // Tina says Hi.
(但这种建立物件的方式,会占用到大量的记忆体,所以之後会补充Prototype的概念。)
那跟今天的主题比较相关的提问是:
( 问题参考自: 前端工程师面试问题集 ★ Front-end Job Interview Questions )
简而言之:
function Person(){}
→ 创造一个建构子Person,可以定义属性和方法,并用於创造object。
var person = Person()
→ 如果没有写new的话,Person就不会创造empty object,this会变成指向浏览器里的window
物件。
→ 而window
里找不到欲定义的属性,那麽建立的person
会回传undefined
。
var person = new Person()
→ new 会创造empty object,赋值给person。
→ person就会是一个可以具备Person()属性,且具有属性值的object。
【如内文有误还请不吝指教>< 感谢阅览至此的各位:D 】
-----正文结束-----
本来是想写this的,但this会用到这个的延伸观念,所以今天来写Constructor Function。
Microsoft 365 DLP(资料外泄防护)警示将协助我们进行调查找出完整的事件范围。 DLP...
Latch 的生成条件 上一篇讲解了什麽是 latch,其又与 flip-flop 差在哪,也解释了...
不管是哪种测试,都是为了确保程序码的品质,以及是否符合需求规格。而单元测试是工程师确保自身产出的一种...
今天要介绍的是Render Functions 先来看一段官网对render function的介绍...
待更新待更新待更新待更新待更新待更新待更新待更新待更新待更新待更新待更新待更新待更新待更新待更新待更...