DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript基礎知識 >> 關於給javascript對象添加、刪除、修改對象的屬性
關於給javascript對象添加、刪除、修改對象的屬性
編輯:JavaScript基礎知識     

以下是自己總結的幾種方法,如有不妥,請君批評指正,不勝感激!

  • 利用動態特性

             function Person(){};
             var person = new Person();
             person.name = 'yy';
             person.gender = 'girl';
             console.log(person.name+','+person.gender);//yy,girl
             delete person.name;//刪除屬性
             console.log(person.name);//undefined
 //            變式
             function Person(){};
             var person = new Person();
             person['name'] = 'yy';
             person['gender'] = 'girl';
             console.log(person.name+','+person.gender);//yy,girl
             delete person.name;//刪除屬性
             console.log(person.name);//undefined                    

 

  • 構造函數中this

var Person = function (){
                this.name = 'yy';
                this.gender = 'girl'
            };
            var person = new Person();
            console.log(person.name+','+person.gender);//yy,girl

 

  • 原型中添加屬性

var Person = function (){    
            };
            Person.prototype.name = 'yy';
            Person.prototype.gender = 'girl';
            var person = new Person();
            console.log(person.name+','+person.gender);//yy,girl
            console.log(person['name']+','+person['gender']);//yy,girl
  • 字面量添加屬性

var person = {    
            };
            person.name = 'yy';
            person.gender = 'girl';
            console.log(person.name+','+person.gender);//yy,girl
            console.log(person['name']+','+person['gender']);//yy,girl
//            另一種寫法
            var person = {
                name: 'yy',
                gender: 'girl'
            };
            console.log(person.name+','+person.gender);//yy,girl
            console.log(person['name']+','+person['gender']);//yy,girl
  • 封裝extend方法

var p1 = {};
            var p2 = {name:'yy',gender:'girl'};
            p1.extend = function(obj){
                for(var k in obj){
                    this[k] = obj[k];
                }
            }
            p1.extend(p2);
            console.log(p1.name+','+p1.gender);//yy,girl
            console.log(p1['name']+','+p1['gender']);//yy,girl
  •  在此列舉了幾種對象添加屬性的方法,那麼對象添加方法也就照貓畫虎了

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved