網(wǎng)站建設(shè)手機版模板愛站網(wǎng)關(guān)鍵詞查詢網(wǎng)站
文章目錄
- 前端知識點---構(gòu)造函數(shù)(Javascript)
- 1. 定義構(gòu)造函數(shù)
- 2. 使用構(gòu)造函數(shù)創(chuàng)建對象
- 3. 工作原理
- 4. 構(gòu)造函數(shù)與原型
- 5. 類的語法糖
- 6. 注意事項
前端知識點—構(gòu)造函數(shù)(Javascript)
在我的文章 “對象” 里我提到了構(gòu)造函數(shù) , 前端知識點—Javascript的對象(Javascript)
因為day14講到了"函數(shù)" , 所以另起一篇文章. 來講構(gòu)造函數(shù) , 這個是屬于比較重要的部分
構(gòu)造函數(shù)是一種用于創(chuàng)建和初始化對象的特殊函數(shù)。一般與new關(guān)鍵字一起使用,來創(chuàng)建具有相同結(jié)構(gòu)和行為的多個對象。是屬于復(fù)雜數(shù)據(jù)類型 , 前面的string , number這些屬于簡單數(shù)據(jù)類型 , 注意把基礎(chǔ)知識捋順 , 面試會考的 .
1. 定義構(gòu)造函數(shù)
1 構(gòu)造函數(shù)作用是初始化對象。定義對象的方法。
2 構(gòu)造函數(shù)的名字通常以大寫字母開頭,以便與普通函數(shù)區(qū)分。普通函數(shù)是小駝峰命名法 .
3 默認返回新創(chuàng)建的對象(除非顯式返回另一個對象)
function Person(name, age) {this.name = name; // 為實例添加屬性this.age = age;this.sayHello = function() {console.log(`My name is ${this.name} , I'm ${this.age} years old now'.`);};
}
里面的this是什么東西呢? 看我另一篇文章 , 我把成塊的知識點寫成專欄方便你們查看前端知識點—this幾種用法
2. 使用構(gòu)造函數(shù)創(chuàng)建對象
要使用構(gòu)造函數(shù)創(chuàng)建對象,需要使用new關(guān)鍵字:
const person1 = new Person("Alice", 25);
const person2 = new Person("Bob", 30);person1.sayHello(); // 輸出: Hello, my name is Alice.
person2.sayHello(); // 輸出: Hello, my name is Bob.
例子
function Person(name, age) {this.name = name; // 為新對象添加 name 屬性this.age = age; // 為新對象添加 age 屬性this.greet = function() { // 定義一個方法console.log(`Hi, my name is ${this.name} and I'm ${this.age} years old.`);};
}// 使用構(gòu)造函數(shù)創(chuàng)建對象
const person1 = new Person('Alice', 25);
const person2 = new Person('Bob', 30);person1.greet(); // Hi, my name is Alice and I'm 25 years old.
person2.greet(); // Hi, my name is Bob and I'm 30 years old.
3. 工作原理
創(chuàng)建新對象:new關(guān)鍵字創(chuàng)建一個空對象。
綁定this:新對象的上下文被綁定到構(gòu)造函數(shù)中的this。
設(shè)置原型:新對象的原型被設(shè)置為構(gòu)造函數(shù)的prototype屬性。
返回對象:構(gòu)造函數(shù)返回這個新對象(如果沒有顯式返回其他對象)。
4. 構(gòu)造函數(shù)與原型
為了節(jié)省內(nèi)存,可以將方法添加到構(gòu)造函數(shù)的prototype上,而不是每次創(chuàng)建對象時都重新定義方法。
function Person(name, age) {this.name = name;this.age = age;
}Person.prototype.sayHello = function() {console.log(`Hello, my name is ${this.name}.`);
};const person1 = new Person("Alice", 25);
const person2 = new Person("Bob", 30);console.log(person1.sayHello === person2.sayHello); // true
5. 類的語法糖
從ES6開始,JavaScript引入了class語法,它本質(zhì)上是對構(gòu)造函數(shù)和原型的封裝,提供了更清晰的語法。
class Person {constructor(name, age) {this.name = name;this.age = age;}sayHello() {console.log(`Hello, my name is ${this.name}.`);}
}const person1 = new Person("Alice", 25);
person1.sayHello(); // 輸出: Hello, my name is Alice.
6. 注意事項
如果構(gòu)造函數(shù)中顯式返回一個對象,new將返回該對象,而不是this。
如果返回的是一個非對象值,new仍會返回this。
function Person(name) {this.name = name;return { greeting: "Hi" }; // 返回這個對象
}const person = new Person("Alice");
console.log(person); // 輸出: { greeting: "Hi" }
總結(jié)
構(gòu)造函數(shù)是JavaScript中創(chuàng)建和初始化對象的一種重要方式。隨著ES6的引入,class語法讓創(chuàng)建對象和定義方法變得更加直觀,但構(gòu)造函數(shù)的底層原理仍然是JavaScript對象創(chuàng)建的核心。