原型

在这里插入图片描述

// 原型 & 原型链
// 什么是原型?: 当我们创建一个新函数时,会为函数创建一个prototype属性,属性指向函数的原型对象
// 什么是原型链?: 对象之间存在继承关系,javascript中通过prototype属性指向父类对象,直到指向object,形成的原型指向的链条,成为原型链
// 构造函数(constructor)?: 原型对象默认有一个constructor属性,包含指向prototype属性所在函数的指针

function Person(){

}
Person.prototype.name = "runzhi"
Person.prototype.getName = function(){
    console.log(this.name)
}
var person1 = new Person()
person1.getName() // runzhi
console.log(person1.hasOwnProperty('name')) // false
console.log("name" in person1) // true -- 原型属性和实例属性都返回true
person1.name = "hhhh"
person1.getName() // hhhh
console.log(person1.hasOwnProperty('name')) // true -- 只有实例属性才会返回true,原型属性返回false
console.log(Person.prototype) // Person { name: 'runzhi', getName: [Function (anonymous)] }
console.log(Person.prototype.constructor) // [Function: Person]
console.log(person1.__proto__) // Person { name: 'runzhi', getName: [Function (anonymous)] }

// 简单的原型写法 -- 对象字面量的形式,这种写法会丢失构造器,若需要,手动定义构造器
function Pers(){

}
Pers.prototype = {
    name: "tttt",
    getName: function(){
        console.log(this.name)
    }
}
var pers = new Pers()
console.log(Pers.prototype.constructor) // [Function: Object]
console.log(pers.__proto__) // { name: 'tttt', getName: [Function: getName] }
console.log(pers.constructor) // [Function: Object]
// 使用上面写法,重写了prototype,constructor指向object

// 通过构造函数创建对象
function Father(name){
    this.name = name
}
var son = new Father("hjiji")
// -- new 创建对象的过程发生了什么
// 创建一个空对象son {}
// son.__proto__ = Father.prototype
// Father.call(this) 重新绑定this,使得构造函数this指向新对象
// 为son赋值属性 son.name
// 返回son

// 实例方法共享
function Star(){
    this.sing = function(){
        console.log("ll")
    }
}
var s1 = new Star()
var s2 = new Star()
console.log(s1.sing === s2.sing) // false -- 直接在构造函数上定义的方法不共享

function Sta(){}
Sta.prototype.sing = function(){
    console.log("ll")
}
var st1 = new Sta()
var st2 = new Sta()
console.log(st1.sing === st2.sing) // true -- 通过原型添加的方法共享


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值