js继承之js原型和原型链的详细介绍

不言
Lepaskan: 2018-08-17 11:36:48
asal
1955 orang telah melayarinya
本篇文章给大家分享的内容是关于js原型和原型链的详细介绍,接下我们就来具体看看js原型继承和js原型链继承的内容,希望可以帮助到大家。

js原型链

所谓言行链就是如果构造函数或对象A,A的原型指向构造函数或对象B,B的原型再指向构造函数或对象C,以此类推,最终的构造函数或对象的原乡指向Object的原型.由此形成一条链状结构,被称之为原型链

js原型链示例代码:

// 原型链
function A(){
    this.a = 'a';
}
// 通过构造函数创建对象
var a = new A();

function B(){
    this.b = 'b';
}
// 将B的原型指向对象a
B.prototype = a;
// 通过构造函数创建对象
var b = new B();

console.log(b.b);// b
console.log(b.a);// a

function C(){
    this.c = 'c';
}
// 将C的原型指向对象b
C.prototype = b;
// 通过构造函数创建对象
var c = new C();

console.log(c.c);// c
console.log(c.b);// b
console.log(c.a);// a
Salin selepas log masuk

js原型链代码分析图:

3026683456-5b75b7df35b4e_articlex.png

只继承于原型

示例代码:

// 原型链
function A(){
    // 将自有属性改写为原型属性
    // this.a = 'a';
}
A.prototype.a = 'a';

function B(){
    // this.b = 'b';
}

// 将B的原型指向
B.prototype = A.prototype;

B.prototype.b = 'b';
/*B.prototype = {
    b : 'b'
}*/

function C(){
    this.c = 'c';
}
// 将C的原型指向
C.prototype = B.prototype;

var c = new C();
console.log(c.c);// c
console.log(c.b);
console.log(c.a);// a
Salin selepas log masuk

js原型链继承实现的问题

1、原型链实际上是在多个构造函数或对象之间共享属性和方法

2、常见子类的对象时,不能像父级的构造函数传递任何参数

注意: 在实际开发中很少会单独使用原型链

示例代码:

// 原型链
function A(){
    // 将自有属性改写为原型属性
    // this.a = 'a';
}
A.prototype.a = 'a';

function B(){
    // this.b = 'b';
}

// 将B的原型指向
B.prototype = A.prototype;

B.prototype.b = 'b';

function C(){
    // this.c = 'c';
}
// 将C的原型指向
C.prototype = B.prototype;
C.prototype.c = 'c';

var c = new C();
console.log(c.c);// 调用结果为 c
console.log(c.b);// 调用结果为 b
console.log(c.a);// 调用结果为 a

var a = new A();

console.log(a.a);// 调用结果为 a
console.log(a.b);// 调用结果为 b
console.log(a.c);// 调用结果为 c

var b = new B();

console.log(b.a);// 调用结果为 a
console.log(b.b);// 调用结果为 b
console.log(b.c);// 调用结果为 c
Salin selepas log masuk

相关推荐:

JS原型和原型链详解

JS核心系列:浅谈原型对象和原型链

Atas ialah kandungan terperinci js继承之js原型和原型链的详细介绍. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!