js原型对象及常见使用情况
prototype 属性的作用
function Cat(name, color) {
this.name = name;
this.color = color;
this.meow = function () {
console.log('喵喵');
};
}
var cat1 = new Cat('大毛', '白色');
var cat2 = new Cat('二毛', '黑色');
cat1.meow === cat2.meow
// false
正常情况下,上述的meow会被调用两次,同一个构造函数的多个实例之间,无法共享属性,从而造成对系统资源的浪费。
但如果cat1和cat2都是白色的情况下,就要写两次白色,很尴尬,所以就有了下面的用法
function Animal(name) {
this.name = name;
}
Animal.prototype.color = 'white'; //直接对原型对象的定义
var cat1 = new Animal('大毛');
var cat2 = new Animal('二毛');
cat1.color // 'white'
cat2.color // 'white'
对于普通函数来说,该属性基本无用。但是,对于构造函数来说,生成实例的时候,该属性会自动成为实例对象的原型。原型对象上添加一个color
属性,结果,实例对象都共享了该属性。
如果想把一个构造函数变成一个数组,就可以用prototype属性指向一个数组,就意味着实例对象可以调用一个数组
prototype
对象有一个constructor
属性,默认指向prototype
对象所在的构造函数
var MyArray = function(){};
console.log(MyArray.prototype.constructor == MyArray) //true prototype原始属性function没有改变
MyArray.prototype = new Array();
console.log(MyArray.prototype.constructor == MyArray) //false prototype已经变成了Array属性
var mine = new MyArray();
console.log(mine.push(1,2,3))
console.log(mine.length) //3
console.log(mine instanceof Array) //true 这里已经变成数组了
constructor的作用
1、constructor属性的作用是,可以得知某个实例对象,到底是哪一个构造函数产生的
function F() {};
var f = new F();
f.constructor === F // true
f.constructor === RegExp // false
2、直接通过一个实例对象新建一个实例
function Constr() {}
var x = new Constr();
var y = new x.constructor();
y instanceof Constr // true
3、构造函数的原型对象单独被更改时,constructor的方法会保留构造函数的原型对象
function Person(name){
this.name = name;
}
var f = new Person();
console.log(f.constructor.name); //Person 获得原型对象的构造函数的名字
console.log(Person.constructor.name);//function 获得构造函数的类型
Person.prototype.constructor === Person //true
Person.prototype = {
method: function(){}
}
Person.prototype.constructor === Person //false
console.log(Person) //[Function: Person]
console.log(Person.prototype.constructor) //[Function: Object]
所以,修改原型对象时,一般要同时修改constructor
属性的指向。
所以有下面的例子:
// 坏的写法
C.prototype = {
method1: function (...) { ... },
// ...
};
// 好的写法
C.prototype = {
constructor: C,
method1: function (...) { ... },
// ...
};
// 更好的写法
C.prototype.method1 = function (...) { ... };
instanceof运算符
概念:
var v = new Vehicle();
原理:instanceof运算符左边是实例对象,右边是构造函数。它会检查右边构造函数的原型对象,是否在左边对象的原型链上
等价写法为: Vehicle.prototype.isPrototypeOf(v)
功能
1、判断对象类型
var obj = { foo: 123 };
obj instanceof Object // true
null instanceof Object // false