程序员

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

2020-06-08  本文已影响0人  Taco_King

JS面向对象

oop

构造函数

是对象的模版

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

对象

创建对象方式

new运算符

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

但实际上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的用法非常相似,区别在于:

封装

把"属性"(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)

原型,原型链

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'

组合模式

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']
上一篇下一篇

猜你喜欢

热点阅读