欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

理解javascript中的原型和原型鏈

 更新時(shí)間:2015年07月30日 09:20:58   作者:放牛娃也有春天  
這篇文章介紹了javascript中的原型和原型鏈,需要的朋友可以參考下

原型

  大家都知道,JavaScript 不包含傳統(tǒng)的類繼承模型,而是使用 prototype 原型模型。代碼實(shí)現(xiàn)大概是這樣子的

function Student(name){
 this.name = name;
}
 
var Kimy = new Student("Kimy");
 
Student.prototype.say = function(){
 console.log(this.name + "say");
}

Kimy.say();
//Kimysay

       Kimy本身是沒有say方法的,當(dāng)他在自己對(duì)象中找不到該方法時(shí)就回去他的原型中查找,也就是Student.prototype對(duì)象中查找。這里我們用到了一個(gè)構(gòu)造函數(shù)Student

構(gòu)造函數(shù)、__proto__以及原型鏈

  除了IE瀏覽器,其他瀏覽器都在Object對(duì)象的實(shí)例上,部署了一個(gè)非標(biāo)準(zhǔn)的__proto__屬性(前后各兩個(gè)下劃線),指向該對(duì)象的原型對(duì)象,即構(gòu)造函數(shù)的prototype屬性。

盜用一段代碼和一張圖

// 構(gòu)造方法
function Foo(y) {
 this.y = y;
}
 
Foo.prototype.x = 10;
 
// 繼承方法"calculate"
Foo.prototype.calculate = function (z) {
 return this.x + this.y + z;
};
 
// 使用foo模式創(chuàng)建 "b" and "c"
var b = new Foo(20);
var c = new Foo(30);
 
// 調(diào)用繼承的方法
b.calculate(30); // 60
c.calculate(40); // 80
 
 
console.log(
 
 b.__proto__ === Foo.prototype, // true
 c.__proto__ === Foo.prototype, // true
 
 b.constructor === Foo, // true
 c.constructor === Foo, // true
 Foo.prototype.constructor === Foo // true
 
 b.calculate === b.__proto__.calculate, // true
 b.__proto__.calculate === Foo.prototype.calculate // true
 
);

  我們可以看到,每個(gè)對(duì)象都是含有一個(gè)__proto__屬性,b的__proto__指向的構(gòu)造b的構(gòu)造方法Foo的prototype屬性;而Foo.prototype也是一個(gè)對(duì)象,本身也有一個(gè)__proto__指向構(gòu)造其的構(gòu)造方法Object的prototype。Object.prototype的__proto__被指向了 null, 這就形成了一個(gè)原型鏈了。

這里還要能理解這樣一段代碼

Object instanceof Function
//true
Function instanceof Object
//true

new做了什么

  這里還有一個(gè)小問(wèn)題,js里面普通函數(shù)和構(gòu)造函數(shù)形式上貌似沒有啥太大區(qū)別(首字母大寫不是必須的,但是通常都把構(gòu)造函數(shù)的首字母大寫)。new這個(gè)關(guān)鍵字到底做了什么東西。

比方

var Kimy = new Student(); 

new 做了三件事情

var Kimy = {}; 

Kimy.__proto__ = Student.prototype;

Student.call(Kimy);

1、定義了一個(gè)空對(duì)象

2、設(shè)置其原型

3、初始化對(duì)象

這樣就能理解為什么Kimy.__proto__指向的是Student.prototype了(同一個(gè)引用),原來(lái)就是new在起著關(guān)鍵的作用!

以上就是本文的全部?jī)?nèi)容,希望大家能夠喜歡。

相關(guān)文章

最新評(píng)論