对js中的原型,原型链,call,applay的理解

原型

  1. 定义:原型是function对象的一个属性,它定义了构造函数制造出的对象的公共祖先,通过该构造函数产生的对象,可以继承该原型的属性和方法,原型也是对象
Person.prototype.name = '小明'
Person.prototype.say = function(){
console.log('hello word')
}
function Person(){}
var person = new Person()
console.log(person.name) //小明
person.say() // hello word
  1. 利用原型特点和概念,可以提取共有属性
function Car(color, owner){
this.owner = owner
this.color = color
this.height = 1400
this.lang = 4900
}
//可以把他们共有的属性提取到prototype上
Car.prototype.height= 1400
Car.prototype.lang = 4900
function Car(color, owner){
this.color = color
this.owner = owner
}
  1. 对象如何查看原型 --> 隐式属性 proto
  2. 对象如何查看对象的构造函数 -->constructor
function Person(){}
Car.prototype = {
constructor: Person
}
function Car(){}
var car = new Car()
console.log(car.constructor) //Person(){}

原型链

Person.prototype.name = 'abc'
function Person(){
var this = {
__proto__:Person.prototype
}
}

var person = new Person();
console.log(person.name) //abc

2.引用值和原始值的区别

Person.prototype.name = 'sunny'
function Person() {}
var person = new Person()
Person.prototype.name = 'cherry'
console.log(person.name) //cherry
Person.prototype.name = 'sunny'
function Person() {}
var person = new Person()
Person.prototype= { name:'cherry'}
console.log(person.name) //sunny
Person.prototype.name = 'sunny'
function Person() {}
Person.prototype.name = 'cherry'
var person = new Person()
console.log(person.name) //cherry

3.绝大多数对象的最终都会继承自Object.prototype

obj.create(null) //prototype : no

call/applay

  1. 作用:改变this指向
  2. 区别:后面传的参数形式不同
function Person(name, age, sex){
this.name = name
this.age = age
this.sex = sex
}
function Student(name,age,sex,grade,tel){
Person.call(this, name, age, sex)
this.grade = grade
this.tel = tel
}

你可能感兴趣的:(对js中的原型,原型链,call,applay的理解)