详细了解JavaScript:它是一个类,一个函数,还是一个变量?

时间:2016-01-01 11:24:24

标签: javascript javascript-objects

我是JavaScript的初学者,我发现一个概念非常令人困惑。请考虑以下代码:

public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();

public CustomListAdapter(Activity activity, List<Movie> movieItems) {
    this.activity = activity;
    this.movieItems = movieItems;
}

@Override
public int getCount() {
    return movieItems.size();
}

@Override
public Object getItem(int location) {
    return movieItems.get(location);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.list_row, null);

    if (imageLoader == null)
        imageLoader = AppController.getInstance().getImageLoader();
    NetworkImageView thumbNail = (NetworkImageView) convertView
            .findViewById(R.id.thumbnail);
    TextView title = (TextView) convertView.findViewById(R.id.title);
    TextView rating = (TextView) convertView.findViewById(R.id.rating);
    TextView genre = (TextView) convertView.findViewById(R.id.genre);
    TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

    // getting movie data for the row
    Movie m = movieItems.get(position);

    // thumbnail image
    thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

    // title
    title.setText(m.getTitle());

    // rating
    rating.setText("Rating: " + String.valueOf(m.getRating()));

    // genre
    String genreStr = "";
    for (String str : m.getGenre()) {
        genreStr += str + ", ";
    }
    genreStr = genreStr.length() > 0 ? genreStr.substring(0,
            genreStr.length() - 2) : genreStr;
    genre.setText(genreStr);

    // release year
    year.setText(String.valueOf(m.getYear()));

    return convertView;
}

}

人是一个阶级或职能还是变量?

如果假设那个人是一个类,那么代码var person = { firstName :"Penelope", lastName :"Barrymore", // Since the "this" keyword is used inside the showFullName method below, and the showFullName method is defined on the person object,​ // "this" will have the value of the person object because the person object will invoke showFullName ()​ showFullName:function () { console.log (this.firstName + " " + this.lastName); } ​ } ​ person.showFullName (); // Penelope Barrymore 是否是调用它的正确方法,因为在C#或我们编写的任何其他语言中

person.showFullName ();

7 个答案:

答案 0 :(得分:39)

person是一个对象。它有3个属性,名为firstNamelastNameshowFullName。前两个属性包含字符串。最后一个属性包含一个函数。

当您使用语法<expression>.<function>(<arguments>)调用函数时,其中<expression>计算对象并且<function>是其属性之一的名称,然后在函数运行时变量this设置为对象。这就是this.firstNamethis.lastName能够访问对象的这些属性的方式。

当只有一个对象时,此功能不是很有用,因为它可以很容易地使用person变量。但是你可以对多个对象使用相同的功能。

function showFull() {
    console.log(this.firstName + " " + this.lastName);
}
var person1 = {
    firstName: "Penelope",
    lastName: "Barrymore",
    showFullName: showFull
};
var person2 = {
    firstName: "John",
    lastName: "Smith",
    showFullName: showFull
}
person1.showFullName(); // Penelope Barrymore
person2.showFullName(); // John Smith

答案 1 :(得分:12)

只是要添加到Barmar,你也可以做到这样的事情(如果你发现它更类似于C#):

var person = function() {
     this.firstName = "";
     this.lastName = "";
} 

person.prototype.showFullName = function () { 
     console.log (this.firstName + " " + this.lastName); 
} 

var perObj = new person();
perObj.firstName = "Penelope";
perObj.lastName = "Barrymore";
perObj.showFullName();

答案 2 :(得分:6)

这是一个对象,而不是一个类。

以这种方式考虑:

在其他经典OO语言中,当您实例化时, 你得到一个实例;这个实例相当于一个JavaScript 对象 -

JavaScript对象是属性的动态“包”。它是一组名称 - 值对,这些值可以是任何类型 - 函数或对象本身。

在您的情况下,-2 * x3是人物对象的适当对象。

使用点(。)表示法访问对象的属性, 例如:firstName, lastName, and showFullName

答案 3 :(得分:4)

person实际上是JavaScript中的对象文字。对象文字是那些被定义为

的文字
var obj = {
    // Properties and methods
};

他们的类型是对象。在JavaScript中,我们没有任何名为 class 的内容。

  • Everything 是一个对象。 (甚至功能)
  

对象文字是以逗号分隔的大括号括起来的名称 - 值对列表。对象文字封装数据,将其封装在整洁的包中。

http://www.dyn-web.com/tutorials/object-literal/

虽然我们确实在ECMAScript 6中有类,但它们并不像其他语言那样是真正的类。

MDN说:

  

ECMAScript 6中引入了JavaScript类,并且语法   优于JavaScript现有的基于原型的继承。该   类语法是引入新的面向对象的继承   模型到JavaScript。 JavaScript类提供了更简单的方法   更清晰的语法来创建对象和处理继承。

答案 4 :(得分:2)

  

人是一个阶级或职能还是变量?

JavaScript没有课程。变量person是指向保存对象的内存位置的变量。

对象本身有几个方面。附加了一组属性,这些属性都附加到person对象。其中一个属性包含一个值,它是一个函数对象。此函数对象包含执行上下文。

Execution ContextECMA 具有本地环境,词汇环境和此绑定。此绑定指向person对象。函数的局部环境作用于函数内部的声明,函数的词法环境作用于Person对象可用的声明。

答案 5 :(得分:0)

代码中的

personobject。换句话说,personObject的一个实例,而person原型与其他对象中的原型相同,由{}初始化程序创建:

// Object initialiser or literal
person = {
  some methods and properties
}

// Called as a constructor
person = new Object({some methods and properties})

这意味着您的person对象会从原型继承对象特定的方法,例如hasOwnProperty()toString()valueOf()等。

最后写的Object constructor不仅可以创建“类似哈希”的对象,还可以创建任何其他类型的对象(数组,字符串等)。 javascript中的所有内容都是对象,甚至是基元(它们是包装对象,并且有自己的构造函数)。

示例:

persons     = new Object([person_1, person_2, person_3])    
person_age  = new Object(18)
person_name = new Object('John')

我们可以用其他语法编写以上所有表达式:

persons     = new Array(person_1, person_2, person_3) //or      
persons     = [person_1, person_2, person_3]

person_age  = new Number(18) //or    
person_age  = 18

person_name = new String('John') //or    
person_name = 'John'

可以使用没有new

的适当全局对象创建字符串和数字

Page on MDN

新对象类型

如果需要创建新类型的对象,必须定义新的构造函数并定义原型(ECMAScript 5.1)

NewObjectType = function(arg1, arg2){
   this.arg1 = arg1 //define object's property arg1
   this.arg2 = arg2 //define object's property arg2

   private_function = function(){}
   this.public_function = function(){} //this function can't be inherited, because not in prototype
}

NewObjectType.prototype = {
   constructor : NewObjectType,
   public_inheritable_function_1 : function(){},
   public_inheritable_function_2 : function(){}
}

//creating new instance of NewObjectType:

my_new_object = new NewObjectType(arg1, arg2)

my_new_object instanceof NewObjectType //true
my_new_object instanceof Object        //true, because prototype was created with {} literal, and Object's prototype built into the prototype chain

<强>解释

调用new NewObjectType时,将创建NewObjectType的新实例。 Prototype构造函数的NewObjectType属性将与新实例的隐藏__proto__属性链接。

没有原型的对象

如果需要在没有Object方法的情况下创建清晰对象,则必须使用create method创建它而不使用原型:

person = Object.create(null)

它可能有用作简单的键值存储

类型,不是从Object继承的

如果需要在原型链中创建没有Object原型的新类型的对象,可以使用以下语法:

NewObjectType = function(arg1, arg2){}
NewObjectType.prototype = Object.create(null)
NewObjectType.prototype.constructor = NewObjectType 
NewObjectType.prototype.public_inheritable_function = function(){}

my_new_object = new NewObjectType(arg1, arg2)

my_new_object instanceof NewObjectType //true
my_new_object instanceof Object        //false

答案 6 :(得分:-1)

JavaScript没有类或不是基于类的语言。相反,我们说它是基于原型的语言。