在javascript中实例化新对象 [英] Instancing new objects in javascript

查看:86
本文介绍了在javascript中实例化新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能缺少了一些真正的关于JavaScript的知识,但是为什么这不起作用?

I'm probably missing something really basic on javascript knowledge, but why doesn't this work?

var person = {

    name:"",
    age:0,

    set : function(name,age){
        this.name = name;
        this.age = age;
    }
}

var me = new person; // ERROR: Object doesn't support this action!
me.set('Victor',12);
me.name //Victor


但是确实如此:


But this does:

var person = function(){

    this.name="";
    this.age=0;

    this.set = function(name,age){
        this.name=name;
        this.age=age;
    }
}

var me = new person(); //WORKS!
me.set('Victor',12);
me.name; //Victor

推荐答案

您的第一个示例是对象文字:

Your first example was an object literal:

var person = {
    name: "Bob",
    //etc
};

您已经创建了一个名为person的对象,仅此而已.创建人的概念没有任何意义.

You've created a single object called person, and that's that. The concept of creating new persons has no meaning.

如果要创建可用于随意创建更多对象的对象,则可以使用函数,例如第二个示例.

If you want to create something that can be used to create more objects at will, you'd use a function, like your second example.

请注意,尽管按惯例约定要用作构造函数的函数以大写字母开头.还要注意,当您使用

Note though that functions intended to be used as a constructor start with a capital letter by convention. Also note that when you set a function inside of your constructor using

this.functionName = function() .....

这将创建一个 privileged 函数,因为它可以访问公共成员和私有成员.如果此设置的函数仅需要访问公共属性,则通常会将其添加到函数的prototype中.这就是整个样子

this creates a privileged function, since it has access to both public, and private members. If this set function only needs access to public properties, it would usually be added to the function's prototype. Here's how the whole thing might look

function Person() {
    this.name = "";
    this.age = 0;
};

Person.prototype.set = function(name,age) {
    this.name = name;
    this.age = age;
}

这就是特权方法的样子

function Person() {
    var localData = "Hello";

    this.showPrivateData = function() {
        alert(localData);
    };

    this.name="";
    this.age=0;
};

localDataPerson函数而言是本地的,不能作为Person实例上的属性进行访问;但是,showPrivateData函数以及您可能添加的任何其他特权函数将在其上形成 closure 并可以访问它.

localData is local to the Person function, and cannot be accessed as a property on instances of Person; however, the showPrivateData function, and any other privileged functions you might add, would form a closure over it, and have access to it.

最后,请注意,构造函数可以使用参数:

Finally, note that constructor functions can take parameters:

function Person(name, age) {
    this.name= name;
    this.age= age;
};

这篇关于在javascript中实例化新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆