JS 对象原型学习笔记function Person(name,age,sex) { this.name = name; this.age = age; this.sex =

function Person(name,age,sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}
//使用原型
Person.prototype.sayName = function(){
    alert(this.name);
}
var p1 = new Person('bob',24,'男');
var p2 = new Person('mary',28,'女');
p1.sayName();//bob
p2.sayName();//mary
alert(p1.hasOwnProperty('name'));//true 给定属性存在于对象实例中时,返回true
for(var key in p1){
    console.log(key);//p1的属性名称,函数的名称
    console.log(p1[key]);//p1的属性值,函数体
}

//判断某个属性是否属于原型
function hasPropertyPrototype(object,name){
    return !object.hasOwnProperty(name) && (name in object);
}

//定义一个日期函数:返回星期几
Date.prototype.sayDay = function(){
    alert(this.getDay());
}
var dd = new Date();
dd.sayDay();

function Dog(){
    this.color = 'black';
}
var dog = new Dog();
alert(dog.color);//black
//重写原型
Dog.prototype = {
    constructor:Dog,
    name:'长江七号',
    age:11,
    sayName:function(){
        alert(this.name);
    }
};
//重写原型,切断了现有原型(Dog)与任何之前已经存在的对象实例(dog)之间的联系,它引用的仍然是最初的原型;
alert(dog.color);//black
alert(dog.name);//undefined
//dog.sayName();//会报错
var dog1 = new Dog();
alert(dog1.age);//11
alert(dog1.color);//black
dog1.sayName();//长江七号

 

 

你可能感兴趣的:(前端)