JavaScript学习要点(四)

来源:互联网 发布:全国软件测试大赛 编辑:程序博客网 时间:2024/05/21 22:31
function hasPrototypeProperty(object, name){
     return !object.hasOwnProperty(name)&&(name in object)
}
//用来判断是否是原型中的变量

先前创建的实例,修改原型后,实例能马上得到原型方法,但重写整个原型后,实例中的指针指向的却还仍然是先前的原型

我们可以通过给原生对象的原型添加方法来对原生对象进行拓展

String.prototype.startWith = function(text){
     return this.indexOf(text) == 0;
};

最常用的方法:构造函数模式用于定义实例属性,而原型模式用于定义方法和共享的属性

function Person(name, age, job){
    this.name = name;
    this.age = age;
    this.job = job;
    this.friend = ["A","B"];
}

Person.prototype = {
    constructoer: Person,
    sayName: function(){
        alert(this.name);
    }
}

var person1 = new Person("A", 29, "AAA");
var Person2 = new Person("B", 27, "BBB");

person1.friend.push("C");
//person1.friend ABC
//person2.friend AB
//perosn1.friend != person2.friend
//person1.sayName == person2.sayName

可以在构造函数中采用这样一种方法,判断若该类型中不含有某函数,就在其函数原型中添加该函数

在构造函数中,首行添加新建对象语句,尾行将其return,叫做寄生构造函数模式

使用稳妥对象的话,只能通过其内部的方法来访问数据成员

ECMAScript中采用原型链作为实现继承的主要方法

原型链的实现
function SuperType() {
    this.property = true;
}

SuperType.prototype.getSuperValue = function(){
    return this.property;
};

function SubType(){
    this.subproperty = false;
}

SubType.prototype = new SuperType();

SubType.prototype.getSubValue = function(){
    return this.subproperty;
};

var instance = new SubType();
alert(instance.getSuperValue()); //true

可通过两种方式来确定原型和实例之间的关系,原型链中出现过的构造函数instanceOf都会返回true

isPrototypeOf也会返回true

用法分别为:
alert(instance instanceOf SubType); //true
alert(instance instanceOf SuperType); //true
alert(instance instanceOf Object); //true

alert(Object.prototype.isPrototypeOf(instance)); //true
alert(SubType.prototype.isPrototypeOf(instance)); //true
alert(SuperType.prototype.isPrototypeOf(instance)); //true

通过原型链实现继承的时候,不能使用对象字面量创建原型方法,这样会重写原型链,会创建一个新的原型

实践中很少单独使用原型链

寄生组合式继承是实现基于类型继承的最有效的方式


0 0
原创粉丝点击