js中的面向对象。

1.js中的面向对象就是类,而类中关键的就是继承

2.首先声明一个类
var Gandparent = function(){
this.game = “play”
}

3.构造函数实现继承

<script type="text/javascript">
    function Grandparent () {

        this.name = "zhangsan"
    }

    Grandparent.prototype.say=function() {
        console.log('jijiko')
    }

    function Son(){
         Grandparent.call(this)
        this.myname = 'cxk'

    }
        console.log(new Son().name)
        console.log(new Son().say())

缺点: 通过构造函数实现继承,只能实现部分继承,原型对象上的属性不能被继承

在这里插入图片描述
4.原型链继承

 function Person() {
        this.age = "50"
        this.friend = ['cxk','ha','du']
    }
    Person.prototype.say=function(){
  		  console.log('cxk ,hello')
    }
    function Man() {
        this.name = "gouzi"
    }
    Man.prototype = new Person()
    let a = new Man()
    let b = new Man()
    a.friend.push('sb')
    虽然可以实现继承,但是new出来的两个实例,其中一个属性变了,另一个也会改变。因为他们是继承的同一个构造函数。
    console.log(new Man().age,new Man().say)
    console.log(a.friend,b.friend)

在这里插入图片描述
5.以上两种方式组合起来

function Person() {
    this.age = "50"
    this.friend = ['cxk','ha','du']
}
Person.prototype.say=function(){
    console.log('cxk ,hello')
}
function Man() {
    Person.call(this)
    this.name = "gouzi"
}
Man.prototype = new Person()
let a = new Man()
let b = new Man()
a.friend.push('sb')
以上两种继承结合可以达到效果,但是每次实例化的时候,都要重复去实例化构造函数
console.log(new Man().age,new Man().say)
console.log(a.friend,b.friend)

在这里插入图片描述
6.优化(继承原型)

function Person() {
    this.age = "50"
    this.friend = ['cxk','ha','du']
}
Person.prototype.say=function(){
    console.log('cxk ,hello')
}
function Man() {
    Person.call(this)
    this.name = "gouzi"
}
Man.prototype = Person.prototype
let a = new Man()
let b = new Man()
a.friend.push('sb')
可以达到相同的效果
console.log(new Man().age,new Man().say)
console.log(a.friend,b.friend)

在这里插入图片描述
7.Object.create(Object.create()方法是ECMAScript 5中新增的方法,这个方法用于创建一个新对象。被创建的对象继承另一个对象的原型,在创建新对象时可以指定一些属性。)

function Person() {
    this.age = "50"
    this.friend = ['cxk','ha','du']
}
Person.prototype.say=function(){
    console.log('cxk ,hello')
}
function Man() {
    Person.call(this)
    this.name = "gouzi"
}
// Man.prototype = Person.prototype
Man.prototype = Object.create(Person.prototype)
let a = new Man()
let b = new Man()
a.friend.push('sb')
同样可以达到效果
console.log(new Man().age,new Man().say)
console.log(a.friend,b.friend)

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/liangkaihuaen/article/details/98506297