2018-11-18 js 面向对象

2018-11-18  本文已影响0人  大妈_b059
// js 会给每个创建的对象设置一个原型,指向它的原型对象
// var arr=[1,2,3];
/**
 * arr对象 其原型对象就是Array,因此js中存在着原型链,arr ----> Array.prototype ----> Object.prototype ----> null
 * 由于js定义了Array.prototype中定义了sort(),indexof()等方法,因此你可以在所有的Array对象上直接调用这些方法。所以可以arr.sort();
 * 在js中函数也是对象。因此函数也有自己的原型链
*/

function student () {
  console.log('测试')
}

// student->Function.prototype->Object.prototype->null,js 创建对象主要由以下两种方法

var lhl = {
  name: 'lhl',
  age: 23,
  hello: function () {
    console.log(`${this.name} 是 ${this.age} 岁 `)
  }
}

lhl.hello()
//  方法二 通过new 关键字来创建

function Student (name) {
  this.name = name
  this.hello = function () {
    console.log(`我是${this.name}`)
  }
};

var lhl = new Student('lhl1')
var lhl2 = new Student('lhl2')

lhl.hello()
lhl2.hello()

// 这里大家会发现,我们每次去重新创建一个学生对象,都会去创建一个hello方法,虽然代码都是一样的,但他们确实两个不同的函数
// 其实这么多对象只需要共享一个hello函数即可,因此根据对象查找原则,我们将hello方法放在Student对象上,便可以实现共享

Student.prototype.hello = function () {
  console.log(`我是${this.name}`)
}

// 此外用new创建的对象,还从其原型对象上获得了一个constructor 属性,它门指向Student对象本身
console.log(lhl.constructor === Student.prototype.constructor) // true
console.log(Student.prototype.constructor === Student)// true
console.log(Object.getPrototypeOf(lhl) === Student.prototype) // true
console.log(lhl instanceof Student) // true

// 下面的一个例子是在廖雪峰老师的教程中看到的一个写法,个人感觉很好,特此记录。

function Teacher (props) {
  this.name = props.name || 'no-name'
  this.age = props.age || 23
}

Teacher.prototype.hello = function () {
  console.log(`${this.name}是${this.age}岁!`)
}

function createTeacher (props) {
  return new Teacher(props || {})
}

var lhl3 = createTeacher({name: 'lhl'})

lhl3.hello()

上一篇 下一篇

猜你喜欢

热点阅读