原型
1、获取对象的原型
let obj={
name:'yrc'
}
// 获取原型对象
// 第一种
console.log(obj.__proto__)//这是浏览器自己定义,有可能存在
// 第二种
console.log(Object.getPrototypeOf(obj))//这是ES5新增的,推荐使用
2、可以在对象的原型上添加属性,但不建议这么做
ps:如果定义对象时没有这个属性message,但是你获取对象时,又object.message,js就会去原型上查找有没有这个属性,没有就undefined
obj.__proto__.message='hellow world'
console.log(obj.message)//hellow world
3、函数也有原型,除了具有对象的__proto__外,还具有对象没有的,function.prototype
let obj={
name:'yrc'
}
function foo(){}
console.log(foo.prototype)
console.log(obj.prototype)//undefined
4、原型的作用
函数原型的作用:当多个对象通过构造函数创建出来后,这多个对象使用的方法有共同方法,如果在普通的构造函数中直接this.function=function(){},这样每次调用都会创建一次,而如果使用Student.prototype.function=function(){},则可以让创建的对象共享这些属性,也就是这些方法,对象的隐式原型指向构造函数的显示原型,这样可以在构造函数的显示原型上放公共属性和方法。
5、原型的内存运行:
6、重写原型对象
7、面向对象的特性:
8、js的原型链
9、继承的实现:
1)错误做法:父类的原型直接赋值给子类的原型
2)方法二:创建一个新的对象作为中转
3)借用构造函数继承
4)最终方案的前身:
5)最终方案:
function createObject(o) {
function F(){}
F.prototype=o
return new F()
}
function inhert(SubType, SuperType) {
// 什么情况均可以使用
var prototype = createObject(SuperType.prototype)
//如果不兼容Object.create,则用上面那行,兼容就用下面那行
// var prototype=Object.create(SuperType.prototype)
SubType.prototype=prototype
Object.defineProperty(prototype, 'constructor', {
value:SubType,
enumerable:false,
configurable:true,
writable:true
})
}
使用
<!--
* @Author:
* @Date: 2024-06-25 22:46:17
* @LastEditors: Please set LastEditors
* @LastEditTime: 2024-10-05 00:51:50
* @Description:
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
</style>
</head>
<body>
<script>
function createObject(o) {
function F(){}
F.prototype=o
return new F()
}
function inhert(SubType, SuperType) {
// 什么情况均可以使用
var prototype = createObject(SuperType.prototype)
//如果不兼容Object.create,则用上面那行,兼容就用下面那行
// var prototype=Object.create(SuperType.prototype)
SubType.prototype=prototype
Object.defineProperty(prototype, 'constructor', {
value:SubType,
enumerable:false,
configurable:true,
writable:true
})
}
function Person(name,age,height) {
this.name=name
this.age=age
this.height=height
}
Person.prototype.running=function(){
console.log('running')
}
function Student(name,age,height,grade,score){
Person.call(this,name,age,height)
this.grade=grade
this.score=score
}
inhert(Student,Person)
Student.prototype.study=function(){
console.log('study')
}
var stu=new Student('yuanrucheng',18,170,'1班','95')
console.log(stu)
</script>
</body>
</html>