JS的继承是基于原型的继承
数组上的方法都是挂载在原型上(Array.prototype)的
obj.proto找到它的原型对象
<!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>
/*继承
JS的继承是基于原型的继承
*/
var arr = [1,2,3];
// toString(); 因为数组的原型上有字符串toString();
/* push,unshift() 因为数组原型上有
*/
/*原型
1.数组上的方法都是挂载在原型上(Array.prototype)的
2.obj.__proto__找到它的原型对象
*/
console.log(arr.toString())
// Array
console.log(Array.prototype);
console.log(arr.__proto__ == Array.prototype);
</script>
</body>
</html>
在数组的原型上添加累加方法
<!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>
/* Function */
var arr = new Array(1,2,3);
/* Array.prototype */
console.log(arr);
/* sum */
var obj = [4,5,6];
Array.prototype.sum = function(params){
if(Array.isArray(params)){
return params.reduce((a,b)=>a+b);
}
}
/*
在数组的原型上添加累加方法
方法名 http
*/
console.log(arr.sum(arr));
console.log(obj.sum(obj));
</script>
</body>
</html>
在数组的原型上添加http方法
<!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>
Array.prototype.http = function(){
console.log("http")
}
/*
在数组的原型上添加http方法
方法名 http
输出 console.log("http")
*/
var arr = [1,2,3];
arr.http()
</script>
</body>
</html>
原型对象
类:对某一个类具体事物的抽象。
对象:某一类事物的具体实例。
原型对象:是某一类对象的基类,所有创建的对象都会共享该原型对象 (共享机制)
作用:将对象通用的方法挂载在原型上
<!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>
// 作用:将对象通用的方法挂载在原型上
function Student(name,age){
this.name = name;
this.age = age;
}
// sayName
Student.prototype.sayName = function(){
console.log(this.name)
}
var s = new Student("zhou",22)
console.log(s);
console.log(Student.prototype);
</script>
</body>
</html>
/*
类:对某一个类具体事物的抽象。
对象:某一类事物的具体实例。
原型对象:是某一类对象的基类,所有创建的对象都会共享该原型对象 (共享机制)
*/
function Teacher(name,age){
this.name = name;
this.age = age;
}
Teacher.prototype.sayName = function(){
console.log(this.name)
}
var p = new Teacher("lisi",20);
// 1.有没有sayName
// 2.为什么有sayName
console.log(p)
原型链proto
var arr = [1,2,3];
// valueOf
// console.log(arr.valueOf())
console.log(arr.__proto__)
console.log(arr.__proto__.__proto__)
// toString
// Array.ptototype
var arr = [1,2,3];
console.log(arr.valueOf());
console.log(arr.__proto__);
// console.log(arr.__proto__.__proto__ == Object.)
instanceof 判断一个对象是不是某个类的实例
var arr = [1,2,3];
// instanceof 判断一个对象是不是某个类的实例
console.log(arr instanceof Array);
function Person(name,age){
this.name = name;
this.age = age;
}
var p = new Person("cheng",12)
console.log(p instanceof Person)