JS原型对象prototype

让我简单的为大家介绍一下原型对象prototype吧!

使用原型实现方法共享

1.构造函数通过原型分配的函数是所有对象所 共享的。

2.JavaScript 规定,每一个构造函数都有一个 prototype 属性,指向另一个对象,所以我们也称为原型对象

3.这个对象可以挂载函数,对象实例化不会多次创建原型上函数,节约内存

4.我们可以把那些不变的方法,直接定义在 prototype 对象上,这样所有对象的实例就可以共享这些方法

5.构造函数和原型对象中的this 都指向 实例化的对象

javascript 复制代码
    function Person(name,age){
        this.name = name
        this.age = age
    }
    // 方法可以共享
    Person.prototype.sing = function(){
        console.log("唱歌")
    }
    let zs = new Person("张三",18)
    zs.sing() // 唱歌
    let ls = new Person("李四",19)
    ls.sing() // 唱歌
    console.log(zs.sing === ls.sing) // true

构造函数里面的 this 指向实例对象

javascript 复制代码
    let that 
    function Person(name, age) {
        that = this
        this.name = name
        this.age = age
    }
    // 构造函数里面的 this 就是实例对象 zs
    let zs = new Person("张三",18)
    console.log(that === zs) // true

原型对象里面的函数 this 指向的还是实例对象

javascript 复制代码
    let that 
    function Person(name) {
        this.name = name
    }
    Person.prototype.sing = function() {
        that = this
        console.log("唱歌")
    }
    let zs = new Person("张三")
    zs.sing()
    console.log(that === zs) // true

感谢大家的阅读,如有不对的地方,可以向我提出,感谢大家!

相关推荐
枯萎穿心攻击5 分钟前
Unity VS UE 性能工具与内存管理
开发语言·游戏·unity·ue5·游戏引擎·虚幻·虚幻引擎
老赵的博客23 分钟前
c++ 常用接口设计
开发语言·c++
binbinaijishu8824 分钟前
Python爬虫入门指南:从零开始的网络数据获取之旅
开发语言·爬虫·python·其他
chenglin01636 分钟前
Logstash_Input插件
java·开发语言
3壹1 小时前
单链表:数据结构中的高效指针艺术
c语言·开发语言·数据结构
WebInfra1 小时前
Rspack 1.5 发布:十大新特性速览
前端·javascript·github
雾恋1 小时前
我用 trae 写了一个菜谱小程序(灶搭子)
前端·javascript·uni-app
不过普通话一乙不改名2 小时前
第四章:并发编程的基石与高级模式之Select语句与多路复用
开发语言·golang
烛阴2 小时前
TypeScript 中的 `&` 运算符:从入门、踩坑到最佳实践
前端·javascript·typescript
JCBP_3 小时前
QT(1)
开发语言·汇编·c++·qt