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

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

相关推荐
GISer_Jing8 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩8 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
AI玫瑰助手9 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车9 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋9 小时前
C++14特性
开发语言·c++·c++14特性
JAVA社区10 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
弥树子10 小时前
踩坑记录:服务器内网调用接口,真实请求URL与官方公开URL不一致问题排查
开发语言·php
z落落11 小时前
C# ToCharArray + foreach遍历 + String与StringBuilder
开发语言·c#
学代码的真由酱11 小时前
Java多用户一对一网页聊天室-测试报告
java·开发语言·功能测试·测试
人道领域11 小时前
【LeetCode刷题日记】669.修剪二叉搜索树
开发语言·python·算法