首頁 > web前端 > js教程 > 每天一篇javascript學習小結(物件導向程式設計)_javascript技巧

每天一篇javascript學習小結(物件導向程式設計)_javascript技巧

WBOY
發布: 2016-05-16 15:31:08
原創
1199 人瀏覽過

1、物件導向的工廠方法

 function createPerson(name, age, job){
   var o = new Object();
   o.name = name;
   o.age = age;
   o.job = job;
   o.sayName = function(){
    alert(this.name);
   }; 
   return o;
  }
  
  var person1 = createPerson("Nicholas", 29, "Software Engineer");
  var person2 = createPerson("Greg", 27, "Doctor");
  
  person1.sayName(); //"Nicholas"
  person2.sayName(); //"Greg"
登入後複製

工廠模型的方法的缺點是會產生大量重複程式碼!

2、建構子模式建立物件

 function Person(name, age, job){
   this.name = name;
   this.age = age;
   this.job = job;
   this.sayName = function(){
    alert(this.name);
   }; 
  }
  
  var person1 = new Person("Nicholas", 29, "Software Engineer");
  var person2 = new Person("Greg", 27, "Doctor");
  
  person1.sayName(); //"Nicholas"
  person2.sayName(); //"Greg"
  
  alert(person1 instanceof Object); //true
  alert(person1 instanceof Person); //true
  alert(person2 instanceof Object); //true
  alert(person2 instanceof Person); //true
  
  alert(person1.constructor == Person); //true
  alert(person2.constructor == Person); //true
  
  alert(person1.sayName == person2.sayName); //false  
登入後複製

 使用new關鍵字建立物件會經歷以下四個過程

  • 1、建立一個新物件
  • 2、將建構子的作用域賦給一個新物件(因此this就指向了這個新物件)
  • 3、執行建構子的方法(為這個新物件賦值)
  • 4、回傳新物件

3、將建構子當函數用

 function Person(name, age, job){
   this.name = name;
   this.age = age;
   this.job = job;
   this.sayName = function(){
    alert(this.name);
   };
  }
  
  var person = new Person("Nicholas", 29, "Software Engineer");
  person.sayName(); //"Nicholas"
  
  Person("Greg", 27, "Doctor"); //adds to window
  window.sayName(); //"Greg"
  
  var o = new Object();
  Person.call(o, "Kristen", 25, "Nurse");
  o.sayName(); //"Kristen"
登入後複製

建構函式當做函式使用就和普通的函式沒有任何不同,它屬於window物件下面新增的方法而已。由於構造函數創建的對象實際上是創建一個新對象,因此在本質上兩者還是不一樣的,還是分離的,他們的方法還是不一樣的!

4、將共有的方法方法全域解決不一致的問題

 function Person(name, age, job){
   this.name = name;
   this.age = age;
   this.job = job;
   this.sayName = sayName;
  }
  
  function sayName(){
   alert(this.name);
  }
  
  var person1 = new Person("Nicholas", 29, "Software Engineer");
  var person2 = new Person("Greg", 27, "Doctor");
  
  person1.sayName(); //"Nicholas"
  person2.sayName(); //"Greg"
  
  alert(person1 instanceof Object); //true
  alert(person1 instanceof Person); //true
  alert(person2 instanceof Object); //true
  alert(person2 instanceof Person); //true
  
  alert(person1.constructor == Person); //true
  alert(person2.constructor == Person); //true
  
  alert(person1.sayName == person2.sayName); //true  
登入後複製

雖然上面的方法解決了一致的問題,但是定義的全局的方法本身屬於window,那麼局部和全局就沒有分開!所以這個方法使用的並不多見!也不建議使用。

5、原型模式

我們創建的任何的一個函數都有一個原型對象,這個屬性是一個指針,它指向一個對象,而這個對象的作用是可以有特定的類型的所有的實例共享的方法!

 function Person(){
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age = 29;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function(){
   alert(this.name);
  };
  
  var person1 = new Person();
  person1.sayName(); //"Nicholas"
  
  var person2 = new Person();
  person2.sayName(); //"Nicholas"
  
  alert(person1.sayName == person2.sayName); //true
  
  alert(Person.prototype.isPrototypeOf(person1)); //true
  alert(Person.prototype.isPrototypeOf(person2)); //true
  
  //only works if Object.getPrototypeOf() is available
  if (Object.getPrototypeOf){
   alert(Object.getPrototypeOf(person1) == Person.prototype); //true
   alert(Object.getPrototypeOf(person1).name); //"Nicholas"
  }
登入後複製

理解原型

無論何時只要是建立了一個函數,就會建立一個原型屬性,這個屬性指向函數的原型物件。在預設的情況下,原型物件都會包含一個constructor(建構函式屬性),這個屬性包含一個指向prototype屬性所在函數的指標!

屬性讀取的順序

每當程式碼讀取某個物件的屬性時候,都會執行一次搜索,目標是具有給定名字的屬性,搜尋從物件的實例本身開始查找,如有則返回,沒有則繼續搜尋該物件的原型鏈,直到搜尋到原型鏈的最外層!

 function Person(){
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age = 29;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function(){
   alert(this.name);
  };
  
  var person1 = new Person();
  var person2 = new Person();
  
  person1.name = "Greg";
  alert(person1.name); //"Greg" 来自实例
  alert(person2.name); //"Nicholas" 来自原型
登入後複製

如果刪除了這個元素的實例屬性

function Person(){
  }
  
  Person.prototype.name = "Nicholas";
  Person.prototype.age = 29;
  Person.prototype.job = "Software Engineer";
  Person.prototype.sayName = function(){
   alert(this.name);
  };
  
  var person1 = new Person();
  var person2 = new Person();
  
  person1.name = "Greg";
  alert(person1.name); //"Greg" ?from instance
  alert(person2.name); //"Nicholas" ?from prototype
  
  delete person1.name;
  alert(person1.name); //"Nicholas" - from the prototype
登入後複製

6、hasOwnProperty方法

這個方法可以偵測一個屬性是否存在於實例中,還是存在於原型中! hasOwnProperty是從Object繼承來的,只要給定屬性存在於物件實例中,才會回傳true.

 function Person(){
    }
    
    Person.prototype.name = "Nicholas";
    Person.prototype.age = 29;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function(){
      alert(this.name);
    };
    
    var person1 = new Person();
    var person2 = new Person();
    
    alert(person1.hasOwnProperty("name")); //false
    alert("name" in person1); //true
    
    person1.name = "Greg";
    alert(person1.name);  //"Greg" ?from instance
    alert(person1.hasOwnProperty("name")); //true
    alert("name" in person1); //true
    
    alert(person2.name);  //"Nicholas" ?from prototype
    alert(person2.hasOwnProperty("name")); //false
    alert("name" in person2); //true
    
    delete person1.name;
    alert(person1.name);  //"Nicholas" - from the prototype
    alert(person1.hasOwnProperty("name")); //false
    alert("name" in person1); //true
登入後複製

7、Object.keys() 可列舉屬性方法

這個方法接收一個物件作為參數,傳回一個包含所有可枚舉屬性的字串陣列

 function Person(){
    }
    
    Person.prototype.name = "Nicholas";
    Person.prototype.age = 29;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function(){
      alert(this.name);
    };
    
    var keys = Object.keys(Person.prototype);
    alert(keys);  //"name,age,job,sayName"
如果想得到所有实例的属性,无论它是否可以枚举都可以使用这个方法来获取
 function Person(){
    }
    
    Person.prototype.name = "Nicholas";
    Person.prototype.age = 29;
    Person.prototype.job = "Software Engineer";
    Person.prototype.sayName = function(){
      alert(this.name);
    };
    
    var keys = Object.getOwnPropertyNames(Person.prototype);
    alert(keys);  //"constructor,name,age,job,sayName"
登入後複製

此方法高版瀏覽器才支援

8、簡單的原型寫法

 function Person(){
    }
    
    Person.prototype = {
      name : "Nicholas",
      age : 29,
      job: "Software Engineer",
      sayName : function () {
        alert(this.name);
      }
    };

    var friend = new Person();
    
    alert(friend instanceof Object); //true
    alert(friend instanceof Person); //true
    alert(friend.constructor == Person); //false
    alert(friend.constructor == Object); //true

登入後複製

重寫了原型就等於將預設的原型方法覆蓋,那麼同樣的建構方法也會被重寫,而重寫的建構方法指向了Object物件!而不是原來的物件Person

如果還是想指向先前的建構方法,可以顯示的指定

 function Person(){
    }
    
    Person.prototype = {
      constructor : Person,
      name : "Nicholas",
      age : 29,
      job: "Software Engineer",
      sayName : function () {
        alert(this.name);
      }
    };

    var friend = new Person();
    
    alert(friend instanceof Object); //true
    alert(friend instanceof Person); //true
    alert(friend.constructor == Person); //true
    alert(friend.constructor == Object); //false

登入後複製

9、原型方法的動態添加

function Person(){
    }
    
    Person.prototype = {
      constructor: Person,
      name : "Nicholas",
      age : 29,
      job : "Software Engineer",
      sayName : function () {
        alert(this.name);
      }
    };
    
    var friend = new Person();
    
    Person.prototype.sayHi = function(){
      alert("hi");
    };
    
    friend.sayHi();  //"hi" ?works!
登入後複製

10、原生物件的原型方法

alert(typeof Array.prototype.sort);     //"function"
    alert(typeof String.prototype.substring);  //"function"

    String.prototype.startsWith = function (text) {//修改原生对象的原型方法
      return this.indexOf(text) == 0;
    };
    
    var msg = "Hello world!";
    alert(msg.startsWith("Hello"));  //true

登入後複製

11、組合使用建構子和原型模式建立物件

//构造函数模式
function Person(name, age, job){
      this.name = name;
      this.age = age;
      this.job = job;
      this.friends = ["Shelby", "Court"];
    }
    //原型模式
    Person.prototype = {
      constructor: Person,
      sayName : function () {
        alert(this.name);
      }
    };
    
    var person1 = new Person("Nicholas", 29, "Software Engineer");
    var person2 = new Person("Greg", 27, "Doctor");
    
    person1.friends.push("Van");
    
    alert(person1.friends);  //"Shelby,Court,Van"
    alert(person2.friends);  //"Shelby,Court"
    alert(person1.friends === person2.friends); //false
    alert(person1.sayName === person2.sayName); //true
登入後複製

12、動態原型模式

function Person(name, age, job){
    
      //properties
      this.name = name;
      this.age = age;
      this.job = job;
      
      //methods
      if (typeof this.sayName != "function"){
      
        Person.prototype.sayName = function(){
          alert(this.name);
        };
        
      }
    }

    var friend = new Person("Nicholas", 29, "Software Engineer");
    friend.sayName();

登入後複製

13、寄生建構子模式

 function Person(name, age, job){
var o = new Object();//依赖全局对象初始化一个对象,然后再返回这个对象
o.name = name;
o.age = age;
o.job = job;
o.sayName = function(){
alert(this.name);
}; 
return o;
}

var friend = new Person("Nicholas", 29, "Software Engineer");
friend.sayName(); //"Nicholas"

function SpecialArray(){ 

//create the array
var values = new Array();

//add the values
values.push.apply(values, arguments);

//assign the method
values.toPipedString = function(){
return this.join("|");
};

//return it
return values; 
}

var colors = new SpecialArray("red", "blue", "green");
alert(colors.toPipedString()); //"red|blue|green"

alert(colors instanceof SpecialArray);

登入後複製

上訴方法有一點說明下,由於它是依賴外層對象來創建一個新對象,因此不能依賴 instanceof方法來確定屬性和方法的來源!它實際上和建構函數的沒有關係!

14、穩健建構子模式

 function Person(name, age, job){
      var o = new Object();
      o.sayName = function(){
        alert(name);
      };  
      return o;
    }
    
    var friend = Person("Nicholas", 29, "Software Engineer");
    friend.sayName(); //"Nicholas"
登入後複製

此方法不依賴任何new this 關鍵符!如果要存取物件的方法和屬性,只能透過物件已經定義好的方法來取得!

15、繼承
javascript實作繼承是透過原型鏈來實現的

function SuperType(){
      this.property = true;//定义一个属性
    }
    
    SuperType.prototype.getSuperValue = function(){//定义的原型方法
      return this.property;
    };
    
    function SubType(){
      this.subproperty = false;
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();
    
    SubType.prototype.getSubValue = function (){
      return this.subproperty;
    };
    
    var instance = new SubType();
    alert(instance.getSuperValue());  //true
    
    alert(instance instanceof Object);   //true
    alert(instance instanceof SuperType);  //true
    alert(instance instanceof SubType);   //true

    alert(Object.prototype.isPrototypeOf(instance));  //true
    alert(SuperType.prototype.isPrototypeOf(instance)); //true
    alert(SubType.prototype.isPrototypeOf(instance));  //true
SubType继承SuperType的方法和属性,因此当instance可以直接调用SuperType的方法!
 function SuperType(){
      this.property = true;
    }
    
    SuperType.prototype.getSuperValue = function(){
      return this.property;
    };
    
    function SubType(){
      this.subproperty = false;
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();
    
    //new method
    SubType.prototype.getSubValue = function (){
      return this.subproperty;
    };
    
    //override existing method
    SubType.prototype.getSuperValue = function (){
      return false;
    };
    
    var instance = new SubType();
    alert(instance.getSuperValue());  //false

登入後複製

上面的例子說明,重寫的原型會覆蓋先前繼承的原型,最後返回的往往不是預期的效果

 function SuperType(){
      this.property = true;
    }
    
    SuperType.prototype.getSuperValue = function(){
      return this.property;
    };
    
    function SubType(){
      this.subproperty = false;
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();
    
    //使用字面量添加的方法导致上面的方法失效了
    SubType.prototype = {
      getSubValue : function (){
        return this.subproperty;
      },
    
      someOtherMethod : function (){
        return false;
      }
    }; 
    
    var instance = new SubType();
    console.log(instance);
    alert(instance.getSuperValue());  //error!
登入後複製

下面的例子也說明重寫原型帶來的風險

 function SuperType(){
      this.colors = ["red", "blue", "green"];
    }

    function SubType(){      
    }
    
    //inherit from SuperType
    SubType.prototype = new SuperType();

    var instance1 = new SubType();
    instance1.colors.push("black");
    alert(instance1.colors);  //"red,blue,green,black"
    
    var instance2 = new SubType();
    alert(instance2.colors);  //"red,blue,green,black"

登入後複製

原型共享导致两个不同的对象调用的同一个数据
16、借用构造函数来实现继承

 function SuperType(){
      this.colors = ["red", "blue", "green"];
    }

    function SubType(){ 
      //inherit from SuperType
      SuperType.call(this);
    }

    var instance1 = new SubType();
    instance1.colors.push("black");
    alert(instance1.colors);  //"red,blue,green,black"
    
    var instance2 = new SubType();
    alert(instance2.colors);  //"red,blue,green"

登入後複製

传递参数

 function SuperType(name){
      this.name = name;
    }

    function SubType(){ 
      //inherit from SuperType passing in an argument
      SuperType.call(this, "Nicholas");
      
      //instance property
      this.age = 29;
    }

    var instance = new SubType();
    alert(instance.name);  //"Nicholas";
    alert(instance.age);   //29

登入後複製

17、组合继承方式

function SuperType(name){
      this.name = name;
      this.colors = ["red", "blue", "green"];
    }
    
    SuperType.prototype.sayName = function(){
      alert(this.name);
    };

    function SubType(name, age){ 
      SuperType.call(this, name);
      
      this.age = age;
    }

登入後複製

18、原型继承

 function object(o){
      function F(){}
      F.prototype = o;
      return new F();
    }
    
    var person = {
      name: "Nicholas",
      friends: ["Shelby", "Court", "Van"]
    };
    
    var anotherPerson = object(person);
    anotherPerson.name = "Greg";
    anotherPerson.friends.push("Rob");
登入後複製

19、寄生组合式继承

 function object(o){
      function F(){}
      F.prototype = o;
      return new F();
    }
  
    function inheritPrototype(subType, superType){
      var prototype = object(superType.prototype);  //create object
      prototype.constructor = subType;        //augment object
      subType.prototype = prototype;         //assign object
    }
                
    function SuperType(name){
      this.name = name;
      this.colors = ["red", "blue", "green"];
    }
    
    SuperType.prototype.sayName = function(){
      alert(this.name);
    };

    function SubType(name, age){ 
      SuperType.call(this, name);
      
      this.age = age;
    }

    inheritPrototype(SubType, SuperType);
    
    SubType.prototype.sayAge = function(){
      alert(this.age);
    };
    
    var instance1 = new SubType("Nicholas", 29);
    instance1.colors.push("black");
    alert(instance1.colors); //"red,blue,green,black"
    instance1.sayName();   //"Nicholas";
    instance1.sayAge();    //29
    
    
    var instance2 = new SubType("Greg", 27);
    alert(instance2.colors); //"red,blue,green"
    instance2.sayName();   //"Greg";
    instance2.sayAge();    //27
登入後複製

以上就是今天的javascript学习小结,之后每天还会继续更新,希望大家继续关注。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板