JS面向对象编程

JavaScript的原型链和Java的Class区别就在,它没有“Class”的概念,所有对象都是实例,所谓继承关系不过是把一个对象的原型指向另一个对象而已。

Object.create()方法可以传入一个原型对象,并创建一个基于该原型的新对象,但是新对象什么属性都没有。

var Student = {
    name: 'Robot',
    height: 1.2,
    run: function () {
        console.log(this.name + ' is running...');
    }
};
var s = Object.create(Student);
console.log(s);
//{}
//__proto__: 
//height: 1.2
//name: "Robot"
//run: ƒ ()
//__proto__: Object
  • 创建对象

 JavaScript为每个创建的对象都会设置一个原型,指向它的原型对象。

例如,创建一个Array对象:
var arr = [1, 2, 3];
其原型链是:
arr ----> Array.prototype ----> Object.prototype ----> null
  arr.indexOf();

Array.prototype定义了indexOf()shift()等方法,因此你可以在所有的Array对象上直接调用这些方法。

当我们创建一个函数时:
function foo() {
    return 0;
}
函数也是一个对象,它的原型链是:
foo ----> Function.prototype ----> Object.prototype ----> null

由于Function.prototype定义了apply()等方法,因此,所有函数都可以调用apply()方法。

  • 构造函数

JavaScript还可以用一种构造函数的方法来创建对象

1.先定义一个构造函数:

function Student(name) {
    this.name = name;
    this.hello = function () {
        alert('Hello, ' + this.name + '!');
    }
}

2.用关键字new来调用这个函数,并返回一个对象

var xiaoming = new Student('小明');
xiaoming.name; // '小明'
xiaoming.hello(); // Hello, 小明!

var xiaoming = Student('小明');
xiaoming.name; // undefined
xiaoming.hello(); // undefined

  新创建的xiaoming的原型链是:

xiaoming ----> Student.prototype ----> Object.prototype ----> null

注意:如果不写new,这就是一个普通函数,它返回undefined

但是,如果写了new,它就变成了一个构造函数,它绑定的this指向新创建的对象,并默认返回this,也就是说,不需要在最后写return this;

new Student()创建的对象还从原型上获得了一个constructor属性,它指向函数Student本身:

Student.prototype.constructor === Student; // true

xiaoming.constructor === Student.prototype.constructor; // true

 现在我们就认为xiaomingxiaohong这些对象“继承”自Student。不过还有一个小问题,注意观察:

xiaoming.name; // '小明'
xiaohong.name; // '小红'
xiaoming.hello; // function: Student.hello()
xiaohong.hello; // function: Student.hello()
xiaoming.hello === xiaohong.hello; // false

xiaomingxiaohong各自的name不同,这是对的,否则我们无法区分谁是谁了。

xiaomingxiaohong各自的hello是一个函数,但它们是两个不同的函数,虽然函数名称和代码都是相同的!

如果我们通过new Student()创建了很多对象,这些对象的hello函数实际上只需要共享同一个函数就可以了,这样可以节省很多内存。

要让创建的对象共享一个hello函数,根据对象的属性查找原则,我们只要把hello函数移动到xiaomingxiaohong这些对象共同的原型上就可以了,也就是Student.prototype

变为

修改代码如下:

function Student(name) {
    this.name = name;
}

Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
};
  • 忘记写new怎么办

为了区分普通函数和构造函数,按照约定,构造函数首字母应当大写,而普通函数首字母应当小写。

我们还可以编写一个createStudent()函数,在内部封装所有的new操作

function Student(props) {
    this.name = props.name || '匿名'; // 默认值为'匿名'
    this.grade = props.grade || 1; // 默认值为1
}

Student.prototype.hello = function () {
    alert('Hello, ' + this.name + '!');
};

function createStudent(props) {
    return new Student(props || {})
}

这个createStudent()函数有几个巨大的优点:一是不需要new来调用,二是参数非常灵活,可以不传,也可以这么传:

var xiaoming = createStudent({
    name: '小明'
});

xiaoming.grade; // 1
  • 原型继承

原文地址:https://www.cnblogs.com/chrisghb8812/p/9565872.html