Javascript 函数对象的属性 [英] Properties of Javascript function objects

查看:31
本文介绍了Javascript 函数对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JavaScript 函数对象;

I have a JavaScript function object as;

var addNum = function(num1, num2) {
        return num1 + num2;
}

现在如果我尝试访问

addNum.divide()

我想了解上述代码的原型链.我在上面的例子中读到,addNum 将搜索divide(),然后是Function.prototype,最后是Object.prototype.

I wanted to understand the prototype chain for the above code. I read that in the above example, addNum would be searched for divide(), followed by Function.prototype and finally Object.prototype.

但我的问题是在上面的例子中,如何在 addNum 中搜索divide()

But my question is in the above example, how can addNum would be searched for divide()

它是否指的是像;

var addNum = function(num1, num2) {

this.divide = function(){}

            return num1 + num2;
    }

我无法理解它说 addNum 将被搜索用于divide() 的那一行

I could not understand the line where it says addNum would be searched for divide()

请帮助我理解相同的内容.

Please help me understand the same.

推荐答案

我不确定这是否能回答您的问题,但可能会给您一些见解.考虑以下示例:

I'm not sure this will answer your question but may give you some insight. Consider the following example:

var Person = (function () {
    var Person = function (name) {
        this.name = name;
    }

    Person.greet = function () {
        console.log("Hello!");
    }

    Person.prototype = {
        greet: function () {
            console.log('Hello, my name is ' + this.name);
        }
    };
    return Person;
})();

var bob = new Person("Bob");

Person.greet(); // logs "Hello!"
bob.greet(); // logs "Hello, my name is Bob

函数对象Person"有一个直接的greet"属性,它是一个函数.在 OOP 方面,您几乎可以将其视为可以直接从 Person 函数 (Person.greet()) 调用的静态方法.一旦你从 Person 构造函数实例化"了一个 person 对象,这个新对象bob"现在从 Person.prototype 对象引用它的方法.现在当你调用 bob.greet() 时,它使用原型对象中的 greet 函数.

The function object "Person" has a direct 'greet' property that is a Function. OOP-wise, you can almost think of that as a static method that can be called directly from the Person Function (Person.greet()). Once you "instantiate" a person object from the Person constructor, that new object "bob" now references it's methods from the Person.prototype object. Now when you call bob.greet(), it uses the greet function in the prototype object.

希望有所帮助.

这篇关于Javascript 函数对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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