JavaScript 面向对象-设计模式
new 做了什么?
- 函数开始隐式创建了一个空对象 ----> new Object() = {}
- 将函数中的 this 指向空对象,在该对象上添加属性和方法 ----> this = {}
- 将该对象的 proto 指向函数的 prototype
- 隐式的返回this
字面量创建
var obj = {}
js
实例化创建
var obj = new Object();
js
工厂模式
function create(name){
var obj = {};
obj.name = name;
return name;
}
var obj = create('xiaoming');
js
构造函数创建
function Person(name){
this.name = name;
}
var person = new Person('小明');
js
原型创建
function Person(){}
Person.prototype.fn = function(){
console.log('共享');
}
var person = new Person();
js
混合创建
function Person(name){
this.name = name;
}
Person.prototype.eat = function(){
console.log('混合创建');
}
var person = new Person('xiaowan');
js
动态混合创建
function Person(name){
this.name = name;
if(typeof this.eat == 'function'){
Person.prototype.ear = function(){
console.log('混合创建');
}
}
}
var person = new Person('xiaoming');
js
JavaScript 面向对象-原型继承
原型链继承
function Person(name){
this.name = name;
}
Person.prototype.fn = function(){
console.log('parent');
}
function Child(){}
Child.prototype = new Person('name');// new 之后 只是实例化的对象,下面有 __proto__
Child.prototype.constructor = Child;// 手动修改回来
var child = new Child();
// 在原型上继承,子类不能修改和传参进去
js
对象冒充继承(借用构造函数
function Parent(name){
this.name = name;
}
Parent.prototype.fn = function(){
console.log('parent');
}
function Child(name){
Parent.call(this,name);
}
var child = new Child('xiaohong');
js
组合继承
function Parent(name){
this.name = name;
}
Parent.prototype.eat = function(){
console.log('11');
}
function Child(name){
Person.call(this,name);
}
Child.prototype.eat = Parent.prototype;
Child.prototype.constructor = Child;
js
寄生式组合继承
function Parent(name){
this.name = name;
}
Parent.prototype.aa = function(){
console.log('aa');
}
function inherit(Child,Parent){
function Super(){};
Super.prototype = Parent.prototype;
Child.prototype = new Super();
Child.prototype.constructor = Child;
}
function Child(){}
inherit(Child,Parent);
var child = new Child();
js
for…in继承
// 遍历父原型对象
for(funName in Person.prototype){
// 子构造函数原型属性 = 父原型对象的属性
NewPerson.prototype[funName] = Person.prototype[funName];
}
js
Object.create()继承
create创建新对象
NewPerson.prototype = Object.create(Person.prototype)
js
JavaScript 检查来自实例还是原型
方法
fn1 instanceof Fun // fn1 是由构造函数 Fun 构造出来的吗?返回 Boolean
Object.getPrototypeOf(Person) // 返回 Person 构造函数的原型
Object.getPrototypeOf(Person) == Person.prototype // true
js
检查来自实例还是原型
Person.hasOwnProperty("fun"); // 是来自实例返回 true,不是返回 false
console.log('name' in a); // 实例或原型上有都返回 true
// 利用hasOwnProperty 与 in 判断到底来自实例还是原型
function hasO(object,name){
return object.hasOwnProperty(name) && (name in object);
// 判断是不是来自实例,如果不是,再in判断是不是原型
}
js
返回实例或原型
将实例保存为数组
function Person(){this.age = 'age';}
Person.prototype.name = "nn";
Person.prototype.sayName = function(){}
var p = new Person();
Object.keys(Person.prototype); // ["name", "sayName"] 原型中的所有实例
Object.keys(p) // ["age"] 只返回p 的实例
Object.getOwnPropertyNames(Person.prototype) // ["constructor", "name", "job", "sayName"] 包含constructor
js