创建对象

来源:互联网 发布:python ma优化 编辑:程序博客网 时间:2024/05/15 03:15
</pre><br />创建单个对象
//对象字面量法var person1 = {    name: "Oneiko",    age: 25,    sayName: function(){        alert(this,name);    }};//alert(person1.name); //Oneiko
//构造函数法var person2 = new Object();person2.name = "Twoiko";person2.age = 26;person2.sayName = function(){    alert(this.name);};//alert(person2.name); //Twoiko
创建多个对象
//工厂模式function createPerson(name,age){    var person = new Object();    person.name = name;    person.age = age;    person.sayName = function(){        alert(this.name);    };    return person;}var person = createPerson("Zeriko",24);//person.sayName(); // Zeriko
//构造函数模式function Person(name,age){    this.name = name;    this.age = age;    /*this.sayName = function(){        alert(this.name);    }*/    this.sayName = sayName;}
function sayName(){    alert(this.name);}
var person3 = new Person("Thriko",27);var person4 = new Person("Fouiko",28);person3.sayName(); //Thrikoperson4.sayName(); //Fouiko//alert(person3.name);//alert(person4.name);
//检测person3是不是Object和Person类型alert(person3 instanceof Object); //truealert(person3 instanceof Person); //true
//原型模式function Person(){}Person.prototype = {    name:"Niko",    age:29,    sayName:function(){        alert(this.name);    }};var person = new Person();person.sayName();var person2 = new Person();person2.sayName();

//组合使用 构造函数模式 和 原型模式
//创建自定义类型的最常见的方式//构造函数模式用于定义特有的实例属性,而原型模式用于定义方法和共享的属性。//结果是每个实例都会有自己的一份实力属性的副本,但同时又共享着对方法的应用function Person(name,age){    this.name = name;    this.age = age;    this.friends = ["Shelby","Court"];}Person.prototype = {    constructor: Person,    sayName: function () {        alert(this.name);    }};var person1 = new Person("Niko",25);var person2 = new Person("Miko",26);person1.friends.push("Viko");alert(person1.friends); //Shelby,Court,Vanalert(person2.friends); //Shelby,Courtalert(person1.friends===person2.friends);//falsealert(person1.sayName===person2.sayName);//true

0 0
原创粉丝点击