waltcow / blog

A personal blog
21 stars 2 forks source link

JS构造函数和原型对象相关总结 #3

Open waltcow opened 7 years ago

waltcow commented 7 years ago

常用的几种对象创建模式

使用new关键字创建

var obj = new Object()
obj.name = 'foo'
obj.age = 24
obj.say = function() {
    console.log(`my name is ${this.name}, age is ${this.age}`)
}

使用字面量创建

var obj = {
    name : "foo",
    age: 24,
    say: function() {
        console.log(`my name is ${this.name}, age is ${this.age}`)
    }
}
// obj 这个对象继承了 Object.prototype 上面的所有属性
// 所以可以这样使用 obj .hasOwnProperty('name').
// hasOwnProperty 是 Object.prototype 的自身属性。
// Object.prototype 的原型为 null。
// 原型链如下:
// o ---> Object.prototype ---> null

工厂模式

function createObj(name, age) {
    var o = new Object();
    o.name = name;
    o.age = age;
    o.say = function() {
        console.log(`my name is ${this.name}, age is ${this.age}`)
    }
    return o;
}
var tom = createObj("tom", 12);
var jack = createObj("jack", 22);

构造函数

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.say = function() {
        console.log(`my name is ${this.name}, age is ${this.age}`)
    }
}
var tom = new Person("tom", 12);
var jack = new Person("jack", 22);

// tom  是生成的对象, 他的自身属性有 'name' 和 'age'.
// 在 tom 被实例化时,tom.[[Prototype]]指向了 Person.prototype.
// tome ---> Person.prototype---> Object.prototype ---> null

注意按照约定构造函数的首字母要大写。 在这里我们创建一个新对象过程如下:

注意:

function CreateObj(x,y) {
  if (this instanceof CreateObj) {
    this.age = x;
    this.name = y
  } else {
    return new CreateObj(x,y);
  }
}

使用Object.create

Object.create(O[, Properties])
returns an object with a prototype of O and properties according to Properties (as if called through Object.defineProperties).

作用的效果可等价于

Object.create = function(O) {  
  function F() {};  
  F.prototype = O;  
  return new F();  
}  
var proto = {
  say: function () {
    console.log(`my name is ${this.name}, age is ${this.age}`)
 }};

var p = Object.create(proto);
p.name = 'kate';
p.age = 12;

p.say() //my name is kate age is 12