-1

我对 javascript 比较陌生,但是从使用 Java 中学到了很多关于 OO 编程的知识。要么 javascript 不是很面向对象,要么我错过了一些东西。Java 的类的方法很像 javascripts 函数,但我注意到 javascript 函数也充当类对象,而不仅仅是方法。如果一个函数可以成为一个对象,我很困惑,该对象不应该能够具有可用的功能吗?

Javascript实现:

function Div() {

var div = document.createElement('div');

 function setSize(width,height){

    div.position = 'absolute';

    div.style.width = width + 'px';
    div.style.height = height + 'px';
    div.style.background = 'black';

    document.body.appendChild(div);


}

}

HTML 脚本

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <script type="text/javascript" src="jWebKit.js"></script>

    <script>

        var div1 = new Div();
        div1.setSize(100,100); //Does Not Work Irritating all whom love Java...

    </script>
</body>
</html>
4

2 回答 2

3

MDN has a nice introduction to OOP. Basically, make div and setSize properties of each instance of Div:

function Div() {
    this.div = document.createElement('div');
}

Div.prototype.setSize = function(width,height) {
    this.div.style.width = width + 'px';
    this.div.style.width = height + 'px';
};

Instance properties are created inside the constructor, "shared" properties between instances are stored on the prototype. ES6 introduces a new class syntax, which is probably closer to what you are used to, but underneath it just creates a constructor function and adds properties to the prototype.

于 2014-06-11T20:18:35.330 回答
1

您的 setSize 方法未定义为此处的类成员,而是定义为范围仅限于该函数的函数。

有很多方法和文档可以解释它是如何工作的,但在这里你可以这样声明你的函数:

function Div() {// Acts as a class?

    this.div = document.createElement('div');
    this.setSize = function(width,height){
        this.div.style.width = width + 'px';
        this.div.style.width = height + 'px';
    }
}
于 2014-06-11T20:25:20.427 回答