创建object对象的几种方法,以及存值取值

创建object对象的几种方法,以及存值取值

//  创建空对象var obj = {};
//  存值两种方式obj[name] = "张三丰";
obg.name = "张三丰";//  取值两种方式var name =obj.name;var name = obj[name];//使用new操作符后跟Object构造函数var person = new Object();
 person.name = "kitty";
 person.age = 25;//  使用“对象字面量”表示法var person = {
      name : "kitty",
      age:25
 };

 var createPerson = function(name,age,job){       var person = new Object();
       person.name = name;
       person.age = age;
       person.job = job;
       person.sayName = function(){
          alert(person.name);
       }       return person;
    }    var person1 = createPerson("zh","62","Doctor");
    person1.sayName();
    {    this.name = name;    this.age = age;    this.job = job;    this.sayName = function(){
       alert(this.name);
    };
  };  var person1 = new Person("zhou",23,"test");
  person1.sayName();

创建对象的例子:

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>javascript 创建对象</title>

<script type="text/javascript" src="js/common.js"></script>

<script type="text/javascript">

println("---对象创建方式---");

//构造函数模式

println("----构造函数模式-----");

function Person(name,color){

this.name = name;

this.color = color;

this.sayName = function(){

println("name = " + this.name);

}

}

var p = new Person("zizhu", "red");

p.sayName();

//原型模式

println("----原型模式-----");

function Dog(){}

Dog.prototype.name = "zizhu8";

Dog.prototype.color = "black";

Dog.prototype.showInfo = function(){

println("name = " + this.name + ", color = " + this.color);

}

var dog = new Dog();

dog.showInfo();

//组合模式

println("----组合模式-----");

function Pig(name,color){

this.name = name;

this.color = color;

}

Pig.prototype.showInfo = function(){

println("name = " + this.name + ", color = " + this.color);

}

var pig = new Pig("pig", "blue");

pig.showInfo();

//动态模式

println("---动态模式---");

function Cow(name,color){

this.name = name;

this.color = color;

if(typeof this.showInfo != "function"){

alert("first alert!!!");

Cow.prototype.showInfo = function(){

println("name = " + this.name + ", color = " + this.color);

}

}

}

var cow = new Cow("cow", "black");

cow.showInfo();

var cow1 = new Cow("cow1", "black1");

cow1.showInfo();

</script>

</head>

<body>

</body>

————————————————

版权声明:本文为CSDN博主「紫竹」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/ziyunyangyong/article/details/8227718

(0)

相关推荐