---
title: "JS面向对象 简单了解"
author: "mowan"
date: "2014-04-28T19:12:00Z"
tags: []
categories: ["编程语言"]
slug: "js"
draft: false
lastmod: "2014-04-28T19:24:08Z"
id: 2056335
url: "https://mowan.iteye.com/blog/2056335"
---

对照Java类分析  每一个Function就是一个对象（类）

```
//构造方法
function HelloWorld(){
    alert("Hello world!");
}
```

   
使用JS中的prototype原型关键字进行赋值，比如为一个对象添加name属性和方法，如下：

```
//添加 成员变量 和 成员方法
HelloWorld.prototype={
    name:'JavaScript',
    sayHello : function(){
        alert(this.name);
    }
} 
```

以上注意sayHello方法中的this关键字使用和Java中this的意思一样。

 

```
//添加 静态属性 和 静态方法
HelloWorld.age = "26";
HelloWorld.hello=function(){
     alert(HelloWorld.age);
}
```

 

不使用Js的原型关键字prototype，声明对象属性和方法，如下：

```
function HelloWorld2(){
    var privateProp = 'hello world 2!';
    this.method = function(){
        alert(privateProp);
    }
    this.name="hammer";
}
```

 针对HelloWorld2测试

```
function _test2(){
    var obj2 = new HelloWorld2();
    obj2.method();
    alert(obj2.name);
    alert(HelloWorld2.privateProp); //undifined
    alert(obj2.privateProp);//undifined
}
```

 

静态方法只能是 类调用

实例方法只能是 实例对象调用