原型图如下
原型
1.定义:原型是function对象的一个属性,它定义了构造函数制造出来的对象的公共祖先.通过该构造函数
产生的对象的公有祖先.通过该构造函数产生对象,可以继承该原型的属性和方法.原型也是对象.
2.利用原型的特点和概念,可以提取共有属性
3.对象如何查看原型->隐式属性 proto
4.对象如何查看对象中的构造函数 -> constructor
1.通过构造函数实例出来的对象都可以继承原型的属性和方法,有同一个公有祖先
Person.prototype.name = 'xxii'; Person.prototype.lastName = 'xb'; function Person(){ this.lastName = 'mm'; } var person = new Person(); console.log(person.name);//xxii console.log(Person.lastName);//mm
- 访问顺序先自己,如果自己有该属性就不看原型的,如果没有往下找(可近的来)
- 可以把(写死)公有部分的放在原型中,需要传参(配置)的放在自身,减少代码的冗余
Car.prototype = {
height: 1400,
lang: 4900,
weight: 1000,
health: 100
}
function Car(name) {
this.name = name;
this.run = function () {
this.health--;
}
}
var car = new Car('BMW');
- 原型的增/删/改/查
Person.prototype.lastName = 'wang';
function Person(name) {
this.name = name
}
var p = new Person('mm');
console.log(p.lastName);//wang
p.lastName = 'xt';
console.log(p.lastName, Person.prototype.lastName);
//xt wang->就是说通过实例不能改原型上的东西,是自己增加了一个属性或者方法
继承发展史
// => 1.传统形式-- > 原型链
//过多的继承了没用的属性
Grand.prototype.lastName = 'Ji';
function Grand() {}
var grand = new Grand();
Father.prototype = grand;
function Father() {
this.name = 'hehe';
}
var father = new Father();
Son.prototype = father;
function Son() { }
// => 2.借用构造函数(工业开发可使用)
// => 不能继承借用构造函数的原型
// => 每次构造函数都要多走一个函数-- > 要new
function Car(name, age, lang) {
this.name = name;
this.age = age;
this.lang = lang;
}
function NCar(color) {
Car.call(this, 'BMW', 2, 4900);
this.color = color;
}
var nCar = new NCar('red');
// => 3.共享原型(多个构造共用一个原型)
Father.prototype.lastName = "jiang";
function Father() { }
function Son() { }
Son.prototype = Father.prototype;
// inhert / extend-- > 单词继承的意思
function Father() { }
function Son() { }
function inherit(Target, Origin) {
Target.prototype = Origin.prototype;
}
inherit(Son, Father);
var son = new Son();
//一定要要先继承后实例化对象
// 缺点:会改变原型的属性和方法, 别的构造函数也受影响了
// => 4.圣杯模式
Father.prototype.lastName = "jiang";
function Father() { };
function Son() { };
function inherit(Target, Origin) {
function F() { };
F.prototype = Origin.prototype;//共享原型
Target.prototype = new F();//继承F构造出来的实例
//这2行不能颠倒,先new F();就已经定音了,继承该实例对象,
//能访问的是该实例对象.protype
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;//超类
}
inherit(Son, Father);
var son = new Son();
var father = new Father();
// => 雅虎 - 圣杯模式
var inherit = (function () {
var F = function () { }//会形成闭包,形成私有化变量了
return function (Target, Origin) {
F.prototype = Origin.prototype;
Target.prototype = new F();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;//超类
}
}());
inherit(Son, Father);
var son = new Son();
var father = new Father();