JS-面向对象-原型对象继承


<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 1. 默认的原型对象继承

        // 原型对象中的所有属性和方法都会被其实例继承,这被称为原型对象继承,这也是 JS 默认的继承方式。

        // 例如,obj1 默认继承了 Object.prototype 原型对象中的所有属性和方法
        var obj1 = {
            name: '杨柯'
        };
        console.log(Object.prototype)
        console.log(obj1)

        // 再例如,arr1 默认继承了 Array.prototype 原型对象中所有属性和方法
        var arr1 = ['red', 'green', 'blue'];

        console.log(Array.prototype)
        console.log(arr1)


        // 原型对象链,arr1.__proto__  ---> Array.prototype.__proto__  ---> Object.prototype
        // 继承链,    arr1 --继承--> Array.prototype --继承--> Object.prototype
        // 因此,arr1 既是 Array 的实例(后代) ,又是 Object 的实例(后代)
        console.log(arr1 instanceof Array);  // true
        console.log(arr1 instanceof Object);  // true

    </script>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在原生 JavaScript 中,可以通过构造函数和原型链来实现面向对象继承。具体实现方式如下: 1. 构造函数继承 构造函数继承是通过在类构造函数中调用父类构造函数来实现的。这种方式的缺点是无法继承父类原型上的方法和属性。 ```javascript function Parent(name) { this.name = name; } function Child(name, age) { Parent.call(this, name); this.age = age; } var child = new Child('Tom', 18); console.log(child.name); // Tom console.log(child.age); // 18 ``` 2. 原型继承 原型继承是通过将类的原型指向父类的实例来实现的。这种方式的缺点是所有类实例共享父类实例上的属性和方法。 ```javascript function Parent() { this.name = 'parent'; } Parent.prototype.sayHello = function() { console.log('Hello'); }; function Child() {} Child.prototype = new Parent(); var child1 = new Child(); var child2 = new Child(); console.log(child1.name); // parent console.log(child2.name); // parent child1.sayHello(); // Hello child2.sayHello(); // Hello ``` 3. 组合继承 组合继承是将构造函数继承原型继承结合起来使用的一种方式。这种方式既可以继承父类实例上的属性和方法,也可以继承父类原型上的属性和方法。 ```javascript function Parent(name) { this.name = name; } Parent.prototype.sayHello = function() { console.log('Hello'); }; function Child(name, age) { Parent.call(this, name); this.age = age; } Child.prototype = new Parent(); Child.prototype.constructor = Child; var child = new Child('Tom', 18); console.log(child.name); // Tom console.log(child.age); // 18 child.sayHello(); // Hello ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值