blog icon indicating copy to clipboard operation
blog copied to clipboard

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

Open waltcow opened this issue 8 years ago • 0 comments

常用的几种对象创建模式

使用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

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

  • 创建一个新的对象,并让 this 指针指向它
  • 将函数的 prototype 对象的所有成员都赋给这个新对象
  • 执行函数体,对这个对象进行初始化操作
  • 返回刚创建的新对象

注意:

  • 如果类中有个 return, 那么就无法返回创建的对象,而返回 return 那句,这样就像没有使用 new 来调用一个函数一样
  • 如果不使用new 调用构造函数,实质上与调用普通的方法函数无异,关键之处在于调用时,所处的作用域为全局作用域, this 指向了 window,也就是说,这次调用发生之后,平白无故的为 window 对象增添了两个属性 name 和 age。 为了解决这种问题,可以在构造函数中检查当前作用域,也就是 this 指向何处
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

waltcow avatar Feb 10 '17 01:02 waltcow