JS中的面向对象

61 阅读1分钟

对象包含什么?

属性和方法

一些内置对象

Object Array Date Function RegExp Math

创建对象的方法

1. 普通方式

每一个对象都要重新写一遍 name 和 run 方法

var obj = new Object();
obj.name = "obj";
obj.run = function() {
    console.log("obj is running");
}

或者工厂模式,这两种方法无法识别对象类型,比如obj的类型只是Object

function createObject() {
    const obj = new Object();
    obj.name = "obj";
    obj.run = function() {
    	console.log("obj is running");
    }
    return obj;
}

2. 构造函数/实例

通过 this 添加的属性和方法总是指向当前对象的,所以在实例化的时候,通过 this 添加的属性和方法都会在内存当中复制一份,这样就会造成内存的浪费 但是这样创建的好处是积是改变了某一个对象的属性或方法,不会影响其他的对象

function Father() {
   this.name = "father";
   this.run = function() {
      console.log("father is running" + new Date());
   }
}
var f1 = new Father();
var f2 = new Father();
console.log(f1.run === f2.run) // 输出false

3. 原型

通过原型继承的方法并不是自身的,我们要在原型链上一层一层的查找,这样创建的好处是只在内存中创建一次,实例化的对象都会指向这个prototype对象

function Father(name) {
    this.name = name;
}
Father.prototype.run = function() {
    console.log("name:" + this.name);
}
const f1 = new Father("f1");
const f2 = new Father("f2");
f1.run();// 输出nme:f1
f2.run();// 输出name:f2
console.log(f1.run === f2.run);// 输出true
  1. 静态属性 是绑定在构造函数上的属性方法,需要通过构造函数访问,比如我们想看一下一共创建了多少Father的实例
function Father(name) {
    this.name = name;
    if(!Father.total) {
        Father.total = 0;
    }
    Father.total++;
}
let f1 = new Father("f1");
console.log(Father.total);// 输出1
let f2 = new Father("f2");
console.log(Father.total);// 输出2