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

查看:115
本文介绍了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()

它指的是类似的东西;

Does it refer to something like ;

var addNum = function(num1, num2) {

this.divide = function(){}

            return num1 + num2;
    }

我无法理解addNum将被搜索为div的行( )

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

请帮我理解一下。

推荐答案

我'我不确定这会回答你的问题,但可能会给你一些见解。请考虑以下示例:

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直接'问候'属性是一个函数。在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天全站免登陆