js下的面向对象
本文記錄了一種Javascript的面向?qū)ο蠓椒霸砝斫?#xff0c;示例代碼如下:
//構(gòu)造函數(shù) var MClass = function(value1, value2) {this.member = "hi";//定義成員屬性Object.defineProperty(this, 'member1', {value: value1});Object.defineProperty(this, 'member2', {value: value2}); }MClass.prototype.member0 = "bao";//原型方法 MClass.prototype.sayHello = function() {console.log(this.member + " " + this.member0);console.log('hello ' + this.member1 + ' And ' + this.member2);return this; }//靜態(tài)方法(類方法) MClass.staticSayHello = function() {console.log('hello ' + this.member0 + " " + this.member);return; }var entity = new MClass('fredric', 'sinny'); MClass.staticSayHello(); entity.sayHello().sayHello();執(zhí)行結(jié)果:
hello undefined undefined hi bao hello fredric And sinny hi bao hello fredric And sinny?//**********************************************************************************************************
補充一些基本概念
1、javascript 中所有都是對象,包含Object,也包括Function;
2、javascript 是一種面向?qū)ο蟮恼Z言,但并非如C++和JAVA一樣是面向類的繼承,而是面向原型的繼承;簡單的講是對象繼承對象;
3、每個javascript對象都會有一個__proto__屬性,這是一個內(nèi)部屬性,指向它繼承的基類對象,這里叫原型對象;
function BASE(){this.x = 1; } BASE.prototype.y = 2; BASE.prototype.func(){ console.log("hello");}如果此時 var a = new BASE(); 那么a的_proto_會指向BASE.prototype,注意沒有this.x屬性;
備注:這里的原型可以以原型鏈的形式不端繼承。
那么x屬性是如何繼承的,我們要打開new的機制,在javascript中這個new其實做了三件事情;
1、創(chuàng)建一個新對象;
2、將新對象的_proto_屬性指向原型,即prototype;
3、調(diào)用BASE的構(gòu)造函數(shù);就是BASE自己,此時a具備屬性x;
因此我是這樣理解的,function也是object,但不等價于object(這里指var a),至少有兩點不同:1、具備構(gòu)造函數(shù),2、可以定義protorype,基于這兩點因素,Function被用來實現(xiàn)javascript下的面向?qū)ο蟆?/span>
下面記錄一個例子:
function TEST(n){this.m = n };var a = new TEST(4);TEST.prototype.test = 1; TEST.prototype.testfunc = function(){console.log("hello"); }//a.prototype.test2 = 3; //編譯出錯 console.log(TEST.constructor);//[Function: Function] console.log(TEST.__proto__);//[Function: Empty] console.log(TEST.prototype);//{ test: 1, testfunc: [Function] } console.log(a.__proto__);//{ test: 1, testfunc: [Function] } console.log(a.constructor);//[Function: TEST] console.log(a.prototype);//undefined console.log(a.m);//4var TEST1 = function(){}; TEST1.prototype = new TEST(3); TEST1.prototype.test1 = 4; console.log(TEST1.prototype);//{ m: 3, test1: 4 } ,這里居然包含了m:3?? console.log(TEST1.__proto__);//[Function: Empty]var b = new TEST1(); console.log(b.__proto__);//{ m: 3, test1: 4 } b.testfunc();//hello console.log(b.__proto__.test1);//4 console.log(b.__proto__.__proto__);//{ test: 1, testfunc: [Function] } 這里是TEST的prototype,原型鏈轉(zhuǎn)載于:https://www.cnblogs.com/Fredric-2013/p/4390441.html
總結(jié)
- 上一篇: vim的使用与配置
- 下一篇: 我的第一份vPlan衍变路线