1. 程式人生 > >javascript 原型屬性(prototype 屬性)與 例項屬性(自身屬性)

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:

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

參照資料: