js 面向對象中,定義一個函數的過程


定義一個函數做的兩件事:
1: 實例化一個Function對象;
2: 實例化一個Object對象,並給該函數擴展prototype屬性指向這個構造函數

 

大致過程如圖所示:

 

每一種引用類型(函數,對象,數組)都有__proto__屬性,並且其__proto__屬性指向其構造模板的prototype(原型對象)。

函數比較特殊,定義一個函數,分為上述兩個步驟。

 

 

驗證:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        //定義構造函數
        function Student(n,a){
            this.name = n;
            this.age = a;
        }
        //原型對象中加入方法
        Student.prototype.sayHi = function(){
            console.log("hello");
        }
        //實例化對象
        var stu = new Student("xiaoming",20);
    </script>
</body>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM