JavaScript对象要点

JavaScript原型使用要点

组合使用构造函数模式和原型模式

代码

//组合使用构造函数模式和原型模式

//构造函数
function Person(name, age, job) {
  //实例属性
  this.name = name;
  this.age = age;
  this.job = job;
  this.friends = ["Shelby", "Court"];
}
//原型
Person.prototype = {
  constructor: Person,//设置constructor值
  //原型方法
  sayName: function() {
    console.log(this.name);
  }
}

//测试代码
var person1 = new Person("Nicholas", 29, "Software Engineer");
var person2 = new Person("Greg", 27, "Doctor");

person1.friends.push("Van");
console.log(person1.friends);
console.log(person2.friends);
console.log(person1.friends === person2.friends);
console.log(person1.sayName === person2.sayName);

结果

[ ‘Shelby’, ‘Court’, ‘Van’ ]

[ ‘Shelby’, ‘Court’ ]

false

true

寄生组合式继承

代码

//寄生组合式继承
function inheritPrototype(subType, superType) {
  var prototype = Object(superType.prototype); //创建对象
  prototype.constructor = subType; //增强对象
  subType.prototype = prototype; //指定对象
}

function SuperType(name) {
  this.name = name;
  this.color = ["red", "blue", "green"];
}

SuperType.prototype.sayName = function() {
  console.log(this.name);
};

function SubType(name, age) {
  SuperType.call(this, name);//在this作用域下调用SuperType构造函数
  this.age = age;
}

inheritPrototype(SubType, SuperType);

SubType.prototype.sayAge = function() {
  console.log(this.age);
}

//测试代码
var sub = new SubType("Damian", 20);
sub.sayName();
sub.sayAge();
console.log(sub.color);

结果

Damian

20

[ ‘red’, ‘blue’, ‘green’ ]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值