[前端] js prototype简单理解

来源:互联网 发布:双枪入洞什么感觉知乎 编辑:程序博客网 时间:2024/06/01 20:40

JS原型prototype学习

1、使用prototype可以扩展对象方法

2、使用prototype可以继承类


已知类a

function a() {    this.name = '张三';    this.say = function() {        alert(this.name);    }}


一、对类a进行方法或属性扩展

a.prototype.spell = function() {    alert('world');}var objA = new a();objA.spell();  // world


a.age = 24;a.prototype.spell = function() {    alert(a.age);}var objA = new a();objA.spell();  // 24

二、原型继承(b的原型是a,相当于b继承了a,包括a的属性和方法)

function b() {}b.prototype = new a();var objB = new b();objB.say();  // 张三

此时console.log一下对象b的原型,会输出

console.log(objB.__proto__);



这里介绍一个prototype与__proto__的区别:

1、prototype是函数的内置属性

2、__proto__是对象的内置属性,用来在js内部寻找原型链


然后再console.log一下对象b的构造函数,会输出

console.log(objB.constructor);



这时使用constructor就可以判断b是否是a的子类了( constructor构造函数,返回对象的构造函数 )

if(objB.constructor == a) {    alert(true);}

还有使用hasOwnProperty()来区别原型方法和原生方法

if(objA.hasOwnProperty('spell') == false) {    console.log('spell不是objA的原生方法');}

等等还有其他方法,如:

isPrototypeOf() 判断谁的原型链中包含了谁的原型(需要两个对象)

var array = [];Array.prototype.say = "Hello";console.log(Array.prototype.isPrototypeOf(array));  // trueconsole.log(array);  // [say: "Hello"]


上述剖析

console.log(typeof Array);  // 函数console.log(Array.prototype);  // 函数原型console.log(typeof new Array());  // 对象(Array函数的实例)console.log(typeof []);  // 对象console.log(typeof array);  // 对象console.log(array.__proto__);  // 对象原型
console.log(Array.prototype);  // [say: "Hello", Symbol(Symbol.unscopables): Object]console.log(array);  // [say: "Hello"]


附:原型链的理解

首先看下下面代码

function a() {    this.say = function() {        console.log(123);    }}var objA = new a();console.log(typeof objA.__proto__);    // objectconsole.log(typeof a.prototype);       // objectconsole.log(typeof Object.prototype);  // objectconsole.log(typeof Object);            // functionconsole.log(typeof String);            // functionconsole.log(typeof Function);          // functionconsole.log(typeof Array);             // function

再来深入理解一下

如果学过java的可能会明白的快些,java的继承是用extends来继承的,而js的对象的继承是用prototype来继承的,所以调用prototype / __proto__属性相当于获取了继承的那个对象

function a() {    this.name = 'john';    this.say = function() {        console.log(this.name);    }}function b() {}b.prototype = new a();var c = new b();console.log(c.__proto__);           // b对象 —— cb的实例,所以c的原型是bconsole.log(b.prototype);           // a对象 —— b的原型对象被赋值了a的实例,所以这里是a对象console.log(a.prototype.__proto__); // Object对象 —— 所有的对象的基类原型对象都是Object,所以a的原型对象是Objectconsole.log(Object.prototype);      // Object对象console.log(c.__proto__.hasOwnProperty('say'));  // trueconsole.log(b.prototype.hasOwnProperty('say'));  // trueconsole.log(a.prototype.hasOwnProperty('say'));  // false


一时不能理解的,多看看,任何东西都经不起重复。。。


谢谢关注~



0 0
原创粉丝点击