如何在 JavaScript 中使用函式構造器呼叫函式?
使用函式構造器呼叫函式會建立一個新的物件。新物件繼承了構造器的屬性和方法。構造器中的this關鍵字沒有值。當函式被呼叫時,這個值將是一個新建立的物件。函式構造建立的函式只在全域性作用域中執行。
在 JavaScript 中,使用函式構造器呼叫函式與將函式作為方法呼叫或將函式作為函式呼叫不同。因為它建立了一個構建屬性和方法的新物件。
語法
以下是使用函式構造器呼叫函式的程式碼片段。在這裡,我們建立了一個函式並傳遞引數,並將這兩個引數繼承到 this 關鍵字的 var1 和 var2 中。
Function functioName(arg1, arg2){
this.var1 = arg1;
this.var2 = arg2;
}
var x = new functionName(1,2) // creating the object
示例:1
在下面的示例中,建立了一個函式和一個函式構造器。函式構造器繼承了函式的屬性。然後我們將值作為物件傳遞。
<!DOCTYPE html>
<html>
<head>
<title>Invoke Function Constructor</title>
</head>
<body>
<script>
function funcDemo(arg1, arg2) {
this.var1 = arg1;
this.var2 = arg2;
}
var obj = new funcDemo(10, 20);
document.write(JSON.stringify(obj));
document.write("<br>")
document.write(obj.var1 + " " + obj.var2);
</script>
</body>
</html>
示例 2
在下面的示例中,我們建立了一個函式構造器,也傳遞了構造器方法。並藉助物件呼叫方法和變數。
<!DOCTYPE html>
<html>
<head>
<title>Invoke Function Constructor</title>
</head>
<body>
<script>
function details() {
this.name = "Aman kumar";
this.age = 23;
this.greet = function () {
document.write("Hello! What is your name and age ?");
};
}
var obj = new details();
obj.greet();
document.write("<br>");
document.write(obj.name + " " + obj.age);
</script>
</body>
</html>
示例 3
在下面的示例中,我們使用了一個名為User的函式構造器並列印使用者的詳細資訊。
<!DOCTYPE html>
<html>
<head>
<title>Invoke Function Constructor</title>
</head>
<body>
<script>
function Users(name, age, state, degree, designation) {
this.name = name;
this.age = age;
this.state = state;
this.degree = degree;
this.designation = designation;
}
const obj = new Users(
"Aman",
23,
"Jharkhand",
"B-Tech",
"technical Writer"
);
document.write(JSON.stringify(obj));
</script>
</body>
</html>
示例 4
讓我們看另一個例子 -
<!DOCTYPE html>
<html lang="en">
<head>
<title>Invoke a function with a function constructor</title>
<div id="getArea"></div>
</head>
<body>
<script type="text/javascript">
let areaFun = function (side1, side2) {
this.length = side1;
this.width = side2;
};
let result = new areaFun(5, 5);
document.getElementById("getArea").innerHTML = JSON.stringify(result);
</script>
</body>
</html>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP