JS面向对象整理篇一——基础概念衍生

106 阅读6分钟

JS面向对象

(持续更新中......)

oop

  • 继承:实例可以继承A对象中的方法和属性,减少代码冗余

  • 封装:对象把实现过程封装在方法中,调用者可以不需了解过程直接调用

  • 多态:一种事物,可以有多种表现形式

构造函数

是对象的模版

function Person(){
    this.name = 'king';
    var age = 12;   // 私有属性,是指针针对实例而言
    this.say = function() {
        console.log('hi~')
    }
}

对象

  • 普通对象: 没有prototype,有__proto__
  • 函数对象: 只有函数有prototype属性,所有的对象都有__proto__隐式属性
  • 实例对象: var son = new Person();

创建对象方式

new运算符

MDN:语法new constructor[([arguments])],创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例

  • 创建一个空的简单JavaScript对象(即{})
  • 链接该对象(即设置该对象的构造函数)到另一个对象
  • 将步骤1新创建的对象作为this的上下文
  • 如果该函数没有返回对象,则返回this

但实际上new具体做了什么操作

var son = new Person();

当这段代码运行的时候,内部实际上执行的是:

// 创建一个空对象
var other = new Object();
// 将空对象的原型赋值为构造函数的原型
other.__proto__ = Person.prototype;
// 改变this指向
Person.call(other);

最后一步如何理解,当构造函数是否返回对象,可做如下尝试

// 无返回对象时
function Person(name){
    this.name = name;
    this.age = 12;
}
Person.prototype.say = function(){
    console.log('say hi')
}
var son = new Person('king');
console.log(son.name);   // 'king'
console.log(son.say());  // 'say hi'

由此可以得出结论,new通过构造函数Person创造出来的实例son,可以访问Person中的内部属性,以及原型链上的方法,当对构造函数Person如下修改时

// 返回非对象
function Person(name){
    this.name = name;
    this.age = 12;
    return 1
}
Person.prototype.say = function(){
    console.log('say hi')
}
var son = new Person('king');
console.log(son.name);   // 'king'
console.log(son.say());  // 'say hi'
// 返回对象
function Person(name){
    this.name = name;
    this.age = 12;
    return {color: 'red'}
}
Person.prototype.say = function(){
    console.log('say hi')
}
var son = new Person('king');
console.log(son);   // '{color: "red"}'

综上,可以很好理解MDN上关于new操作符的最后一步操作结果

Object.create()

语法:Object.create(proto[, propertiesObject]),创建一个新对象,使用现有的对象来提供新创建的对象的__proto__

内部实现方式

Object.create =  function (o) {
    // o参数是原型对象,不需要加.prototype
    var F = function () {};
    F.prototype = o;
    return new F();
};
Object.create = function (obj) {
    var B={};
    Object.setPrototypeOf(B,obj); // or  B.__proto__=obj;
    return B;  
};
MDN demo:
const person = {
  isHuman: false,
  printIntroduction: function() {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};

const me = Object.create(person);

console.log(me): // {}
me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten

me.printIntroduction();
// expected output: "My name is Matthew. Am I human? true"

第二个参数

//该参数是一个属性描述对象,它所描述的对象属性,会添加到实例对象,作为该对象自身的属性。
var obj = Object.create({}, {
  p1: {
    value: 123,
    enumerable: true,
    configurable: true,
    writable: true,
  },
  p2: {
    value: 'abc',
    enumerable: true,
    configurable: true,
    writable: true,
  }
});

// 等同于
var obj = Object.create({});
obj.p1 = 123;
obj.p2 = 'abc';

个人感觉跟new的用法非常相似,区别在于:

  • 字面量和new关键字创建的对象是Object的实例,原型指向Object.prototype,继承内置对象Object

  • Object.create(proto, propertiesObject)创建的对象的原型取决于proto,proto为null,新对象是空对象,没有原型,不继承任何对象;proto为指定对象,新对象的原型指向指定对象,继承指定对象。propertiesObject是可选参数,指定要添加到新对象上的可枚举的属性(即其自定义的属性和方法,可用hasOwnProperty()获取的,而不是原型对象上的)的描述符及相应的属性名称,如果不传则实例对象为{}。

  • Object.create(o),如果o是一个构造函数,则采用这种方法来创建对像没有意义

  • Object.create(o),如果o是一个字面量对象或实例对象,那么相当于是实现了对象的浅拷贝

封装

把"属性"(property)和"方法"(method),封装到一个构造函数里,并且他的实例对象可以继承他的所有属性和方法,构建构造函数

prototype

解决所有实例指向prototype对象地址,而不需要每个实例对象重复生成构造内部属性方法,这意味着,我们可以把那些不变的属性和方法,直接定义在prototype对象上,被构造函数实例继承

// before 
function Person(name){
    this.name = name;
    this.say = function(){
        console.log('say hi');
    }
}
//after
function Person(name){
    this.name = name;
    this.age = 12;
}
Person.prototype.say = function(){
    console.log('say hi')
}
var son = new Person('king');
var daughter = new Person('kim');

isPrototypeOf()用来判断,某个proptotype对象和某个实例之间的关系; Person.prototype.isPrototypeOf(son) // true hasOwnProperty()判断某一个属性到底是本地属性,还是继承自prototype对象的属性; son.hasOwnProperty("age") //false in运算符还可以用来遍历某个对象的所有属性,包含继承的属性 for(var prop in son)

原型,原型链

  • 内置对象:Object、Function都是js内置的函数, 类似的还有我们常用到的Array、RegExp、Date、Boolean、Number、String

  • js分为函数对象和普通对象,每个对象都有__proto__属性,但是只有函数对象才有prototype属性

  • 除了Object的原型对象(Object.prototype)的__proto__指向null,其他内置函数对象的原型对象和自定义构造函数的__proto__都指向Object.prototype, 因为原型对象本身是普通对象

function F(){};
F.prototype.__proto__ = Object.prototype;
Array.prtotype.__proto__ = Object.prototype;
Object.prototype.__proto__ = null;

F.__proto__ = Function.prototype;

var f = new F();
f.__proto__ = F.prototype;

继承

  • 构造函数继承
function Person(name){
    this.name = name
}
function Son(name){
    Person.call(this,name)
}
var obj = new Son('king');
console.log(obj.name)  // 'king'
  • prototype模式

组合模式

function Person(age){
    this.age = age
}
function Son(age){
    this.name = 'king';
    Person.call(this,age);
}
// 改变Son的prototype指向Person的实例,那么Son的实例就可以继承Person
Son.prototype = new Person();
console.log(Son.prototype.constructor == Person.prototype.constructor)  //true
// 避免继承链混乱,将Son.prototype对象的constructor改回Son
Son.prototype.constructor = Son;
var obj = new Son(12);
console.log(obj.age)  // 'king'
console.log(Person.prototype.isPrototypeOf(obj)) // true 同时继承Person和Son
function Person(){

}
Person.prototype.age = 12;
function Son(name){
    this.name = name;
}
// Son.prototype指向Person.prototype
Son.prototype = Person.prototype;
console.log(Son.prototype.constructor == Person.prototype.constructor)  //true
// 然而也修改了Person.prototype.constructor为Son
Son.prototype.constructor = Son;
var obj = new Son('king');
console.log(obj.age)  // 'king'
console.log(Person.prototype.isPrototypeOf(obj)) // true 同时继承Person和Son
Son.prototype.sex = 'male';
console.log(Person.prototype.sex);  // 'male'

差别:与前一种方法相比,这样做的优点是效率比较高(不用执行和建立Person的实例了),比较省内存。缺点是 Person.prototype和Son.prototype现在指向了同一个对象,那么任何对Son.prototype的修改,都会反映到Person.prototype,再次改进如下,

利用空对象作为中介

function Person(){
    this.age = 12
}
Person.prototype.sex = 'male';
function Son(){
    this.name = 'king';
}
var F = function(){};
F.prototype = Person.prototype;
Son.prototype = new F();
Son.prototype.constructor = Son;
Son.uber = Person.prototype;
var obj = new Son();
console.log(obj.sex);  // 'male'

// 封装一下
function extend(Child, Parent){
    var F = function(){};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;
}
extend(Son,Parent);
var obj = new Son();
console.log(obj.sex);  // 'male'
  • 拷贝继承

利用 for...in 拷贝Person.prototype上的所有属性给Son.prototype,Son的实例就相当于继承了Person.prototype的所有属性以及Son的属性

  • 非构造函数继承

1.json格式的发明人Douglas Crockford,提出了一个object()函数,即后来的内置函数Object.create()

function object(o){
    var F = function(){};
    F.prototype = o;
    return new F();
}
var child = {
    name: 'child'
}
var parent = {
    name: 'parent'
}
var child = object(parent)
console.log(child.name);   // 'parent'

2.浅拷贝

var parent = {
    area: ['A','B']
}
function extendCopy(o){
    var c = {};
    for(var i in o){
        c[i] = o[i]
    }
    return c;
}
var child = extendCopy(parent);
child.area.push('C');
console.log(parent.area);  // ['A','B','C']

现象:当父对象的属性值为数组或者对象时,子对象改变那个属性值,父对象也会随之改变,因此,子对象只是获得了内存地址,而不是真正的拷贝,extendCopy只能用作基本数据类型的拷贝,这也是早期jquery实现继承的方式

3.深拷贝

var parent = {
    area: ['A','B']
}
function deepCopy(p,c){
    var c = c || {};
    for(var i in p){
        if(typeof p[i] === 'object'){
            c[i] = (p[i].constructor === Array) ? [] : {};
            deepCopy(p[i],c[i]);
        }else {
            c[i] = p[i]
        }
    }
    return c;
}
var child = deepCopy(parent);
child.area.push('C');
console.log(parent.area);  // ['A','B']