js对象原型、原型链

2016-11-24  本文已影响0人  angelwgh

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


设置对象原型

Object.creat

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

Object.create(proto, [ propertiesObject ])
  //定义原型对象
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";

构造函数

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

上一篇 下一篇

猜你喜欢

热点阅读