js下的面向对象

时间:2023-04-10 21:36:20

本文记录了一种Javascript的面向对象方法及原理理解,示例代码如下:

//构造函数
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;
} //静态方法(类方法)
MClass.staticSayHello = function() {
console.log('hello ' + this.member0 + " " + this.member);
return;
} var entity = new MClass('fredric', 'sinny');
MClass.staticSayHello();
entity.sayHello().sayHello();

执行结果:

hello  undefined undefined
hi bao
hello fredric And sinny
hi bao
hello fredric And sinny

//**********************************************************************************************************

补充一些基本概念

1、javascript 中所有都是对象,包含Object,也包括Function;

2、javascript 是一种面向对象的语言,但并非如C++和JAVA一样是面向类的继承,而是面向原型的继承;简单的讲是对象继承对象;

3、每个javascript对象都会有一个__proto__属性,这是一个内部属性,指向它继承的基类对象,这里叫原型对象;

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、创建一个新对象;

2、将新对象的_proto_属性指向原型,即prototype;

3、调用BASE的构造函数;就是BASE自己,此时a具备属性x;

因此我是这样理解的,function也是object,但不等价于object(这里指var a),至少有两点不同:1、具备构造函数,2、可以定义protorype,基于这两点因素,Function被用来实现javascript下的面向对象。

下面记录一个例子:

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);// var 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);//
console.log(b.__proto__.__proto__);//{ test: 1, testfunc: [Function] } 这里是TEST的prototype,原型链