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)); // true
console.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__); // object
console.log(typeof a.prototype); // object
console.log(typeof Object.prototype); // object
console.log(typeof Object); // function
console.log(typeof String); // function
console.log(typeof Function); // function
console.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对象 —— c是b的实例,所以c的原型是b
console.log(b.prototype); // a对象 —— b的原型对象被赋值了a的实例,所以这里是a对象
console.log(a.prototype.__proto__); // Object对象 —— 所有的对象的基类原型对象都是Object,所以a的原型对象是Object
console.log(Object.prototype); // Object对象
console.log(c.__proto__.hasOwnProperty('say')); // true
console.log(b.prototype.hasOwnProperty('say')); // true
console.log(a.prototype.hasOwnProperty('say')); // false
欢迎关注分享录:http://fenxianglu.cn/