1.1:原型怎麼寫?
1.2:prototype的特點是什麼?
1.3:物件的三角戀關係是怎麼樣的?
建構函式名.prototype=
{
函數名:function()
{
console.log("原型的寫法");
}
}
原型怎麼寫?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
/*let fns={
mySay:function()
{
console.log("7");
}
}*/
function Person(myName, myAge)
{
this.name = myName;
this.age = myAge;
//this.say=fns.mySay;
//可以簡化為:
/*this.say=function()
{
console.log("7");
}*/
}
Person.prototype={
say:function()
{
console.log("666");
}
};
let obj1 = new Person("lnj", 34);
obj1.say();
let obj2 = new Person("zs", 44);
obj2.say();
console.log(obj1.say === obj2.say); // true,因為都是在同一個原型裡面找到的.構造方法裡面沒有say函數.
</script>
</body>
</html>
1.建立物件後,建構函式裡面找不到就去原型裡面找.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>99-JavaScript-prototype特點</title>
<script>
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
this.currentType = "建構函式中的type";
this.say = function () {
console.log("建構函式中的say");
}
}
Person.prototype = {
currentType: "人",
say: function () {
console.log("hello world");
}
}
let obj1 = new Person("lnj", 34);
obj1.say();
console.log(obj1.currentType);
let obj2 = new Person("zs", 44);
obj2.say();
console.log(obj2.currentType);
</script>
</head>
<body>
</body>
</html>
1.記住,是構造方法裡面沒有才去原型裡面找的哈,比如我有錢我為什麼要去借錢是吧.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>100-JavaScript-物件三角戀關係</title>
<script>
function Person(myName, myAge) {
this.name = myName;
this.age = myAge;
}
let obj1 = new Person("lnj", 34);
//這裡代表的都是指向哪裡的哈.
console.log(Person.prototype);
console.log(Person.prototype.constructor);
console.log(obj1.__proto__);
</script>
</head>
<body>
</body>
</html>
每個「建構函式」中都有一個預設的屬性,叫做prototype,prototype屬性儲存著一個物件,這個物件我們稱之為「原型物件」。
每個「原型物件」中都有一個預設的屬性,叫做constructor , constructor指向當前原型物件對應的那個「建構函式」。
通過建構函式建立出來的物件,我們稱之為「範例物件」, 每個「範例物件」中都有一個預設的屬性,叫做__proto__, __proto__指向建立它的那個建構函式的「原型物件」。**
三角戀圖: