js对象原型、原型链


title: js对象原型、原型链
date: 2016-11-24 18:54:08
tags: javascript
categories:

  • javascript

设置对象原型

Object.creat

Object.create() 方法创建一个拥有指定原型和若干个指定属性的对象。

Object.create(proto, [ propertiesObject ])
  • 参数
    • proto
      • 一个对象,作为新创建对象的原型。
    • propertiesObject
      • 可选。该参数对象是一组属性与值,该对象的属性名称将是新创建的对象的属性名称,值是属性描述符(这些属性描述符的结构与Object.defineProperties()的第二个参数一样)。注意:该参数对象不能是 undefined,另外只有该对象中自身拥有的可枚举的属性才有效,也就是说该对象的原型链上属性是无效的。
  • 抛出异常
    • 如果 proto 参数不是 null 或一个对象值,则抛出一个 TypeError 异常。
  //定义原型对象
var landRover = {
    name: 'landRover',
    start:function(){
        console.log('%s start',this.logo)
    },
    run:function(){
        console.log('%s running',this.logo)
    },
    stop:function(){
        console.log('%s stop',this.logo)
    }
}

  //使用原型构造新的对象
var landWind = Object.create(landRover);
landWind.logo = "landWind";

var landCruiser = Object.create(landRover);
landCruiser.logo = "landCruiser";

构造函数

  • 构造函数使用prototype设置原型
  • 使用new关键字创建对象
Car的构造函数
function Car(logo){
    this.log = logo || 'unknow name';
}

//设置Car的prototype属性
Car.prototype = {
    start:function(){
        console.log('%s start',this.logo)
    },
    run:function(){
        console.log('%s running',this.logo)
    },
    stop:function(){
        console.log('%s stop',this.logo)
    }
}

//创建对象
var landWind = new Car('landWind');
var landRover = new Car('landRover');

原型链

//Car的构造函数
function Car(logo){
    this.log = logo || 'unknow name';
}

//设置Car的prototype属性
Car.prototype = {
    start:function(){
        console.log('%s start',this.logo)
    },
    run:function(){
        console.log('%s running',this.logo)
    },
    stop:function(){
        console.log('%s stop',this.logo)
    }
}

// landRover构造函数
function LandRover(serialno){
    this.serialNumber = serialno
}

// 设置LandRover的prototype属性
LandRover.prototype = new Car('landRover');

landRover1 = new landRover(10001)

landRover1的原型指向Car的实例,这个实例的原型指向Car的prototype,Car.prototype的原型又指向Object.prototype,这一系列构建了一条原型链

而构造函数LandRover和Car作为函数对象,其对象原型(proto)指向Function.prototype,Function.prototype指向Object.prototype

你可能感兴趣的:(js对象原型、原型链)