javascript 原型屬性(prototype 屬性)與 實例屬性(自身屬性)

講到原型屬性,prototype屬性,實例屬性,自身屬性,首先我們要明白這四者之間的關係。我查了一些資料,原型屬性又叫prototype屬性,實例屬性又叫自身屬性。只是叫法不同。下面我要引用他人寫的一段代碼來加以說明:

1:實例屬性指的是在構造函數方法中定義的屬性,屬性和方法都是不一樣的引用地址例如:

function CreateObject(name,age){
    this.name=name;  //實例屬性
    this.age=age;
    this.run=function(){   //實例方法
        return this.name + this.age;
    }

    //可以設置全局方法來實現引用地址一致性 .會出現問題
    //this.run = run;
}


var box1 = new CreateObject('ZHS',100);
var box2 = new CreateObject('ZHS',100);


console.log(box1.name == box2.name);//true
console.log(box1.run() == box2.run());//true
console.log(box1.run == box2.run); //false 比較的是引用地址

如何讓box1,和box2run方法的地址一致呢?使用冒充
例如:

//對象冒充
var o = new Object();
Box.call(o,'xlp',200);
console.log(o.run());

2.原型屬性指的是不在構造函數中定義的屬性,屬性和方法都是一樣的引用地址,例如

function CreateObject(){}
CreateObject.prototype.name='ZHS';
CreateObject.prototype.age='100';
CreateObject.prototype.run=function(){
    return this.name + this.age;
}

var CreateObject1 = new CreateObject();
var CreateObject2 = new CreateObject();
console.log(CreateObject1.run == CreateObject2.run); //true
console.log(CreateObject1.prototype);//這個屬性是個對象,訪問不了
console.log(CreateObject1.__proto__);//這個屬性是個指針指向prototype原型對象
console.log(CreateObject1.constructor);//構造屬性
如果我們在CreateObject1 添加自己屬性呢?例如
CreateObject1.name='XLP';
console.log(CreateObject1.name);// 打印XLP //就近原則
可以使用delete刪除實例屬性和原型屬性
delete CreateObject1.name;  //刪除實例中的屬性
delete CreateObject.prototype.name ;//刪除原型中的屬性

爲了更進一步說明prototype屬性,在此我再增加一段代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script type="text/javascript">
    function employee(name,age,address){
        this.name=name;
        this.age=age;
        this.address=address;

        this.hello=function(){
            return "名字:"+this.name+";"+"年齡:"+this.age+";"+"地址:"+this.address;
        }
    }

    var employ1=new employee("小歐",23,"浙江衢州");
    employee.prototype.country="中國";
    document.write(employ1.country);
    document.write("<br>");
    document.write(employ1.hello());

</script>
</body>
</html>

ouput:

中國
名字:小歐;年齡:23;地址:浙江衢州

實例化的對象可以共享原型對象的所有屬性與方法。

例子如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<script type="text/javascript">
    function createPerson(name,age,address){
        this.name=name;
        this.age=age;
        this.address=address;
        this.sayname=function (){
            return this.sex;
        }
    }

    createPerson.prototype.sex="女";

    var Obj=new createPerson("xiaohong",25,"武漢");
    document.write(Obj.sex);
    document.write("<br>");
    document.write(Obj.sayname());


</script>
</body>
</html>

output:

通過上面的例子可以看出,我在實例方法中照樣可以訪問下面所定義的原型屬性的值。

參照資料:

http://cnodejs.org/topic/518a3adc63e9f8a5420df3b4

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章