0
点赞
收藏
分享

微信扫一扫

面向对象-原型

<!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>

</body>
<script>
function Fn(n) {
this.name = n;
this.show = function(){
console.log(this.name)
}
}
var f1 = new Fn("admin");
var f2 = new Fn("root");
console.log(f1 == f2) //f
f1.show();
f2.show();
console.log(f1.show == f2.show) //f



console.log(Fn)
console.dir(Fn)
console.dir(Fn.prototype)
console.dir(Fn.__proto__)

// prototype:函数的原型属性(对象):做什么的?将来被new出来的对象的父级
// constructor:表示当前对象所属的函数,表示自己属于哪个函数

// __proto__:数据的原型链,js中所有数据,都有这个属性,表示:自己的父级

Fn.qwe = function(){};
Fn.prototype.qwe = function(){};

console.log(f1)
console.log(f2)
console.log(f1.__proto__.qwe)
console.log(f1.__proto__ === Fn.prototype)
console.log(f2.__proto__ === Fn)

// 函数的父级(来源):Function()
// f1的父级(来源):Fn.prototype
// f2的父级(来源):Fn.prototype

// String()
// Number()
// Boolean()
// Array()
// Object()
// Function()

// =====================================


function Fun(n){
this.name = n;
}

Fun.prototype.show = function(){
console.log(this.name)
}

console.log(Fun.prototype)

var f1 = new Fun("admin");
var f2 = new Fun("root");

console.log(f1 === f2)

console.log(f1.show === f2.show);//true
console.log(f1.__proto__ === f2.__proto__);//true
console.log(f1.__proto__.show === f2.__proto__.show);//true

f1.__proto__.show();
f2.__proto__.show();

console.log(f1)
console.log(f2)

f1.show();
f2.show();

console.log(f1.show == f2.show)

// 当对象访问自身属性或方法时,如果自身有,直接使用
// 如果自身没有,会顺着__proto__找自己的父级身上是否存在,有,就使用,没有,继续向上找,到顶之后,还没有,就抛出undefined


// ============================

var arr1 = new Array(3,4,5)
var arr2 = new Array(3,4,5)
console.log(arr1 == arr2)
console.log(arr1)
console.log(arr2)

// arr1.push
// arr2.push

console.log(arr1.push === arr2.push)//true

// ==================================

// 面向对象的过程中:
// 将属性写在构造函数内
// 将方法写在构造函数的原型上


// 实例:实际的案例
// 构造函数(类)是实例的抽象化
// 实例是构造函数(类)的具象化

 

长风破浪会有时,直挂云帆济沧海



举报

相关推荐

原型及面向对象相关内容

0 条评论