我想知道创建具有属性和方法的JavaScript对象的最佳方法是什么。

我见过有人用var self = this然后用self的例子。在所有函数中确保作用域总是正确的。

然后我看到了使用.prototype来添加属性的例子,而其他人则是内联的。

谁能给我一个适当的例子,一个JavaScript对象的一些属性和方法?


当前回答

我经常使用这种模式——我发现当我需要它的时候,它给了我相当大的灵活性。在使用中,它非常类似于java风格的类。

var Foo = function()
{

    var privateStaticMethod = function() {};
    var privateStaticVariable = "foo";

    var constructor = function Foo(foo, bar)
    {
        var privateMethod = function() {};
        this.publicMethod = function() {};
    };

    constructor.publicStaticMethod = function() {};

    return constructor;
}();

它使用在创建时调用的匿名函数,返回一个新的构造函数。因为匿名函数只被调用一次,所以可以在其中创建私有静态变量(它们在闭包内部,对类的其他成员可见)。构造函数基本上是一个标准的Javascript对象——你在里面定义私有属性,公共属性附加到this变量上。

基本上,这种方法将Crockfordian方法与标准Javascript对象结合起来,以创建更强大的类。

你可以像使用其他Javascript对象一样使用它:

Foo.publicStaticMethod(); //calling a static method
var test = new Foo();     //instantiation
test.publicMethod();      //calling a method

其他回答

另一种方法是http://jsfiddle.net/nnUY4/ (我不知道这种处理对象创建和显示函数是否遵循任何特定的模式)

// Build-Reveal

var person={
create:function(_name){ // 'constructor'
                        //  prevents direct instantiation 
                        //  but no inheritance
    return (function() {

        var name=_name||"defaultname";  // private variable

        // [some private functions]

        function getName(){
            return name;
        }

        function setName(_name){
            name=_name;
        }

        return {    // revealed functions
            getName:getName,    
            setName:setName
        }
    })();
   }
  }

  // … no (instantiated) person so far …

  var p=person.create(); // name will be set to 'defaultname'
  p.setName("adam");        // and overwritten
  var p2=person.create("eva"); // or provide 'constructor parameters'
  alert(p.getName()+":"+p2.getName()); // alerts "adam:eva"

继续鲍恩斯的回答

在es6中,你现在可以创建一个类

现在你可以这样做:

class Shape {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }

    toString() {
        return `Shape at ${this.x}, ${this.y}`;
    }
}

所以延伸到一个圆(就像在另一个答案中一样)你可以这样做:

class Circle extends Shape {
    constructor(x, y, r) {
        super(x, y);
        this.r = r;
    }

    toString() {
        let shapeString = super.toString();
        return `Circular ${shapeString} with radius ${this.r}`;
    }
}

最终在es6中更干净,更容易阅读。


下面是一个很好的例子:

类形状{ 构造函数(x, y) { 这一点。X = X; 这一点。Y = Y; } toString () { 返回' Shape at ${this。x} $ {this.y} '; } } 类Circle扩展形状{ 构造函数(x, y, r) { 超级(x, y); 这一点。R = R; } toString () { let shapeString = super.toString(); 返回半径为${this.r}的圆形${shapeString}; } } let c = new Circle(1,2,4); Console.log (" + c, c);

当一个人在构造函数调用期间使用关闭“this”的技巧时,是为了编写一个函数,可以被其他不希望调用对象上的方法的对象用作回调。这与“使范围正确”无关。

这是一个普通的JavaScript对象:

function MyThing(aParam) {
    var myPrivateVariable = "squizzitch";

    this.someProperty = aParam;
    this.useMeAsACallback = function() {
        console.log("Look, I have access to " + myPrivateVariable + "!");
    }
}

// Every MyThing will get this method for free:
MyThing.prototype.someMethod = function() {
    console.log(this.someProperty);
};

阅读Douglas Crockford关于JavaScript的文章,您可能会学到很多东西。约翰·瑞西格也很出色。好运!

基本上在JS中没有类的概念,所以我们使用函数作为与现有设计模式相关的类构造函数。

//Constructor Pattern
function Person(name, age, job){
 this.name = name;
 this.age = age;
 this.job = job;
 this.doSomething = function(){
    alert('I am Happy');
}
}

到目前为止,JS还不知道你想要创建一个对象,所以这里有一个新的关键字。

var person1 = new Person('Arv', 30, 'Software');
person1.name //Arv

参考:专业JS网页开发人员- Nik Z

除了2009年接受的答案。如果你可以瞄准现代浏览器,你可以使用Object.defineProperty。

Object.defineProperty()方法直接在上定义一个新属性 对象,或修改对象上的现有属性,并返回 对象。 来源:Mozilla

var Foo = (function () {
    function Foo() {
        this._bar = false;
    }
    Object.defineProperty(Foo.prototype, "bar", {
        get: function () {
            return this._bar;
        },
        set: function (theBar) {
            this._bar = theBar;
        },
        enumerable: true,
        configurable: true
    });
    Foo.prototype.toTest = function () {
        alert("my value is " + this.bar);
    };
    return Foo;
}());

// test instance
var test = new Foo();
test.bar = true;
test.toTest();

要查看桌面和移动兼容性列表,请参见Mozilla的浏览器兼容性列表。是的,IE9+和Safari手机版一样支持。