5

在 JavaScript 中,我看到了几种不同的方式,可以在对象中执行某些任务,例如我下面的对象 Egg。

谁能告诉我每个之间的区别,为什么我会使用一个而不是另一个等

 var Egg = function(){

    //Properties

    var shell = "cracked" // private property 

    this.shell = "cracked" // public property

    shell: "cracked" // what is this??

    //functions

    function cook(){

        //standard function
    }

    cook: function(){
        //what kind of function is this?
    }

    //not sure what this is

    details: {
        //What is this? an array :S it holds 2 elements?
        cost: 1.23,
        make: 'Happy Egg';
    }




}
4

4 回答 4

6

您的代码片段不太有效,但它提出了以下几点:

属性初始化器、对象初始化器

你问的是什么shell: cracked。它是一个属性初始化器。您可以在对象初始值设定项(又名“对象文字”)中找到它们,它们的写法如下:

var obj = {
    propName: "propValue"
};

这相当于:

var obj = {};
obj.propName = "propValue";

以上两者都创建了一个对象,该对象具有一个名为的属性,该属性propName具有一个字符串 value "propValue"。请注意,this它不会进入它。

职能

有几个地方通常会针对对象使用函数:

构造函数

构造函数,它们是您通过new操作符调用的函数。这是一个例子:

// Constructor function
function Foo(name) {
    this.name = name;
}

// Usage
var f = new Foo("Fred");

请注意其中关键字的使用this。这就是你看到的地方(很可能)。当你通过 调用构造函数时newthis指的是new操作符创建的新对象。

thisthis在 JavaScript 中是一个滑溜的概念(与C++、Java 或 C# 中的完全不同),我在我的博客上推荐这两个(咳咳)帖子:

生成器/工厂函数

您不必使用构造函数和new,另一种模式使用“builder”或“factory”函数代替:

// A factory function
function fooFactory(name) {
    var rv = {}; // A new, blank object

    rv.name = name;

    return rv;
}

// Usage
var f = fooFactory("Fred");

私人财产

您在问题中提到了“私有”属性。JavaScript 根本没有私有属性(不过,它们正在开发中)。但是您会看到人们通过将他们在对象上使用的函数定义为执行上下文(通常是对构造函数或工厂函数的调用)的闭包来模拟它们,其中包含其他人无法看到的变量,如下所示:

// Constructor function
function EverUpwards() {
    var counter = 0;

    this.increment = function() {
        return ++counter;
    };
}

// Usage:
var e = new EverUpwards();
console.log(e.increment()); // "1"
console.log(e.increment()); // "2"

(该示例使用构造函数,但您可以使用工厂函数执行相同的操作。)

请注意,即使我们分配给的功能increment可以访问counter,但其他任何东西都不能。counter实际上是私有财产。这是因为该函数是一个闭包。更多:闭包并不复杂

于 2012-07-19T17:18:03.450 回答
4

当然,本。

这种方式触及了 JavaScript 活力的底层。首先,我们将了解基础知识——如果您来自了解基于类的语言的地方,例如 Java 或 C++/C#,那么最有意义的是构造函数模式很早就包括在内:

function Egg (type, radius, height, weight) {
    // private properties (can also have private functions)
    var cost = (type === "ostrich") ? 2.05 * weight : 0.35 * weight;

    // public properties
    this.type = type;
    this.radius = radius;
    this.height = height;
    this.weight = weight;
    this.cracked = false;

    // this is a public function which has access to private variables of the instance
    this.getCost = function () { return cost; };
}

// this is a method which ALL eggs inherit, which can manipulate "this" properly
// but it has ***NO*** access to private properties of the instance
Egg.prototype.Crack = function () { this.cracked = true; };


var myEgg = new Egg("chicken", 2, 3, 500);

myEgg.cost; // undefined
myEgg.Crack();
myEgg.cracked; // true

这很好,但有时有更简单的方法来解决问题。有时你真的不需要上课。

如果你只是想用一个鸡蛋怎么办,因为这就是你的食谱所要求的?

var myEgg = {};  // equals a new object
myEgg.type = "ostrich";
myEgg.cost = "......";
myEgg.Crack = function () { this.cracked = true; };

这很好,但那里仍然有很多重复。

var myEgg = {
    type : "ostrich",
    cost : "......",
    Crack : function () { this.cracked = true; }
};

这两个“myEgg”对象完全相同。

这里的问题是 myEgg 的每一个属性和每一个方法对任何人都是 100% 公开的。

解决方案是立即调用函数:

// have a quick look at the bottom of the function, and see that it calls itself
// with parens "()" as soon as it's defined
var myEgg = (function () {
    // we now have private properties again!
    var cost, type, weight, cracked, Crack, //.......

    // this will be returned to the outside var, "myEgg", as the PUBLIC interface
    myReturnObject = {
        type : type,
        weight : weight,
        Crack : Crack, // added benefit -- "cracked" is now private and tamper-proof
        // this is how JS can handle virtual-wallets, for example
        // just don't actually build a financial-institution around client-side code...
        GetSaleValue : function () { return (cracked) ? 0 : cost; }
    };

    return myReturnObject;
}());

myEgg.GetSaleValue(); // returns the value of private "cost"
myEgg.Crack();
myEgg.cracked // undefined ("cracked" is locked away as private)
myEgg.GetSaleValue(); // returns 0, because "cracked" is true

希望这是一个不错的开始。

于 2012-07-19T17:33:30.280 回答
1

您正在混合对象属性声明和简单的 javascript 语句之间的语法。

// declare an object named someObject with one property
var someObject = {
    key: value
};

// declare an anonymous function with some statements in it
// and assign that to a variable named "someFunction"
var someFunction = function () {
    // any javascript statements or expressions can go here
};
于 2012-07-19T17:12:19.830 回答
0

在 JavaScript 中,对象和函数之间有一个关键的区别。对象包含一堆数据(包括函数),函数可以用来制作或修改对象,但它们本质上不是一回事。JavaScript 中的 OOP 是基于将函数用作类。例如,参加以下课程:

Test = function(){
    this.value = 5;
}

如果你只是调用函数Test(),那么什么都不会发生。即使你说var x = Test(),x 的值也会undefined。然而,使用new关键字,奇迹发生了!因此,如果我们说var x = new Test(),那么现在变量x将包含一个 Test 对象。如果你这样做console.log(x.value),它将打印 5。

这就是我们可以使用函数来制作对象的方式。语法上还有一个关键的不同——一个函数可以包含你想要的任何类型的 JavaScript 块,无论是 if 语句还是 for 循环或者你有什么。但是,在声明对象时,您必须使用key: value语法。

希望能把事情弄清楚一点!

于 2012-07-19T17:14:37.307 回答