一、前言

       接着上一篇的内容,继续JavaScript的学习。

 

二、内容

       属性类型

//数据属性
[Configurable] —— 能否通过delete删除属性从而重新定义属性,能否修改属性的特性,或者修改为访问器属性 默认为true
[Enumerable] —— 能否通过for-in循环返回属性 默认为true
[Writeable] —— 能否修改属性的值 默认为true
[Value] —— 包含这个属性的数据值 默认为undefined


//要修改属性默认的特性,必须使用Object.defineProperty()
var person = {};
Object.defineProperty(person,"name",{
writable:false,
value:"Nicholas"
});

alert(person.name); //"Nicholas"
person.name = "Greg"
//无效

          创建对象

//hasOwnProperty()与in操作符
object.hasOwnProperty("propertyName") //在原型中返回false,在实例中返回true;
"propertyName" in object //无论存在于实例还是原型都返回true

Object.keys(object.prototype); //取得对象上所有可枚举的实例属性
Object.getOwnPropertyNames(object.prototype) //取得对象上所有实例属性,无论是否枚举

//组合使用构造函数模式与原型模式
创建自定义类型的最常见方式,就是组合使用构造函数模式与原型模式。
定义实例属性 —— 构造函数模式
定义方法和共享属性 —— 原型模式

//传统方式
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby","Court"];
}
Person.prototype = {
constructor:Person,
sayName: function(){
alert(this.name);
}
}

//动态原型方式
function Person(name,age,job){
this.name = name;
this.age = age;
this.job = job;
this.friends = ["Shelby","Court"];
if(typeof this.sayName != "function"){
Person.prototype.sayName = function(){
alert(this.name);
};

}
}

         继承

//确定原型和实例的关系
alert(instance instanceof Object); //true
alert(Object.prototype.isPrototypeOf(instance)); //true


//伪造对象或经典继承
function SuperType(){
this.colors = ["red","blue","green"];
}

function SubType(){
SuperType.call(this);
}

//组合继承 —— 需要两次调用超类型构造函数
function SuperType(name){
this.name = name;
this.color = ["red","blue","green"];
}
SuperType.prototype.sayName = function(){
alert(this.name);
}


function SubType(name,age){
//继承属性
SuperType.call(this,name); //第二次
this.age = age;
}
//继承方法

SubType.prototype = new SuperType(); //第一次
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
alert(this.age);
}

//原型式继承
var person = {
name:"Nicholas",
friends:["Shelby","Court","Van"]
};

var anotherPerson = Object.create(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");

//或
var anotherPerson = Object.create(person,{
name:{
value:"Greg"
}
});


//寄生式继承
function createAnother(original){
var clone = object(original);
clone.sayHi = function(){
alert("Hi");
};
return clone;
}
var anotherPerson = createAnother(person);
anotherPerson.sayHi();


//寄生组合式继承 —— 一次调用超类型的构造函数
继承属性 —— 借用构造函数
继承方法 —— 原型链的混成形式

function inheritPrototype(subType,superType){
var prototype = object(superType.protoType);
prototype.constructor = subType;
subType.prototype = protype;
}

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

function SubType(name,age){
//继承属性
SuperType.call(this,name);
this.age = age;
}

inheritPrototype(SubType,SuperType);
SubType.prototype.sayAge = function(){
alert(this.age);
}

 

posted on 2018-02-09 14:38  airforce094  阅读(217)  评论(0编辑  收藏  举报