Hướng dẫn how to echo the value of a static property in javascript? - làm thế nào để lặp lại giá trị của một thuộc tính tĩnh trong javascript?

Tôi đã thấy một vài câu trả lời tương tự, nhưng tôi muốn đề cập rằng bài đăng này mô tả nó tốt nhất, vì vậy tôi muốn chia sẻ nó với bạn.

Dưới đây là một số mã được lấy từ nó, mà tôi đã sửa đổi để có được một ví dụ hoàn chỉnh mà hy vọng mang lại lợi ích cho cộng đồng vì nó có thể được sử dụng làm mẫu thiết kế cho các lớp.

Nó cũng trả lời câu hỏi của bạn:answers your question:

function Podcast[] {

    // private variables
    var _somePrivateVariable = 123;

    // object properties [read/write]
    this.title = 'Astronomy Cast';
    this.description = 'A fact-based journey through the galaxy.';
    this.link = '//www.astronomycast.com';

    // for read access to _somePrivateVariable via immutableProp 
    this.immutableProp = function[] {
        return _somePrivateVariable;
    }

    // object function
    this.toString = function[] {
       return 'Title: ' + this.title;
    }
};

// static property
Podcast.FILE_EXTENSION = 'mp3';
// static function
Podcast.download = function[podcast] {
    console.log['Downloading ' + podcast + ' ...'];
};

Với ví dụ đó, bạn có thể truy cập các thuộc tính/hàm tĩnh như sau:static properties/function as follows:

// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'

Và các thuộc tính/hàm đối tượng chỉ đơn giản là:object properties/functions simply as:

// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123

Lưu ý rằng trong podcast.immutableProp [], chúng tôi có một đóng cửa: tham chiếu đến _sOmeprivateVarable được giữ bên trong hàm. that in podcast.immutableProp[], we have a closure: The reference to _somePrivateVariable is kept inside the function.

Bạn thậm chí có thể xác định getters và setters. Hãy xem đoạn mã này [trong đó

// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
2 là nguyên mẫu của đối tượng mà bạn muốn khai báo một thuộc tính,
// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
3 là một biến riêng tư không hiển thị bên ngoài hàm tạo]:getters and setters. Take a look at this code snippet [where
// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
2 is the object's prototype for which you want to declare a property,
// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
3 is a private variable not visible outside of the constructor]:

// getters and setters
var d = Date.prototype;
Object.defineProperty[d, "year", {
    get: function[] {return this.getFullYear[] },
    set: function[y] { this.setFullYear[y] }
}];

Nó xác định thuộc tính

// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
4 qua các hàm
// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
5 và
// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
6 - nếu bạn không chỉ định
// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
6, thì thuộc tính chỉ được đọc và không thể sửa đổi [lưu ý bạn sẽ không gặp lỗi nếu bạn cố gắng đặt nó, nhưng nó không có hiệu ứng]. Mỗi thuộc tính có các thuộc tính
// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
8,
// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
9 [cho phép thay đổi sau khi khai báo] và
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
0 [cho phép sử dụng nó làm bảng điều khiển], theo mặc định
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
1. Bạn có thể đặt chúng qua
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
2 trong tham số thứ 3, ví dụ:
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
3.

Điều gì cũng hợp lệ là cú pháp này:

// getters and setters - alternative syntax
var obj = { a: 7, 
            get b[] {return this.a + 1;}, 
            set c[x] {this.a = x / 2}
        };

trong đó xác định một thuộc tính có thể đọc/có thể ghi

// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
4, thuộc tính đọc
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
5 và thuộc tính chỉ ghi
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
6, thông qua đó có thể truy cập thuộc tính
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
4.

Usage:

console.log[obj.a]; console.log[obj.b]; // output: 7, 8
obj.c=40;
console.log[obj.a]; console.log[obj.b]; // output: 20, 21

Notes:

Để tránh hành vi bất ngờ trong trường hợp bạn đã quên từ khóa

// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
8, tôi khuyên bạn nên thêm mục sau vào chức năng
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
9:

// instantiation helper
function Podcast[] {
    if[false === [this instanceof Podcast]] {
        return new Podcast[];
    }
// [... same as above ...]
};

Bây giờ cả hai lần khởi tạo sau đây sẽ hoạt động như mong đợi:

var podcast = new Podcast[]; // normal usage, still allowed
var podcast = Podcast[];     // you can omit the new keyword because of the helper

Câu lệnh 'mới' tạo ra một đối tượng mới và sao chép tất cả các thuộc tính và phương thức, tức là

var a=new Podcast[];
var b=new Podcast[];
a.title="a"; b.title="An "+b.title;
console.log[a.title]; // "a"
console.log[b.title]; // "An Astronomy Cast"

Ngoài ra, lưu ý rằng trong một số tình huống, có thể hữu ích khi sử dụng câu lệnh

// getters and setters
var d = Date.prototype;
Object.defineProperty[d, "year", {
    get: function[] {return this.getFullYear[] },
    set: function[y] { this.setFullYear[y] }
}];
0 trong hàm hàm tạo
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
9 để trả về một đối tượng tùy chỉnh bảo vệ các chức năng mà lớp dựa vào bên trong nhưng cần phải được phơi bày. Điều này được giải thích thêm trong Chương 2 [đối tượng] của loạt bài viết.
that in some situations it can be useful to use the
// getters and setters
var d = Date.prototype;
Object.defineProperty[d, "year", {
    get: function[] {return this.getFullYear[] },
    set: function[y] { this.setFullYear[y] }
}];
0 statement in the constructor function
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
9 to return a custom object protecting functions the class internally relies on but which need to be exposed. This is explained further in chapter 2 [Objects] of the article series.

Bạn có thể nói rằng

// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
4 và
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
5 kế thừa từ
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
9. Bây giờ, điều gì sẽ xảy ra nếu bạn muốn thêm một phương thức vào podcast áp dụng cho tất cả chúng sau khi
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
4 và
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
5 đã được khởi xướng? Trong trường hợp này, hãy sử dụng
// getters and setters
var d = Date.prototype;
Object.defineProperty[d, "year", {
    get: function[] {return this.getFullYear[] },
    set: function[y] { this.setFullYear[y] }
}];
7 như sau:

Podcast.prototype.titleAndLink = function[] {
    return this.title + " [" + this.link + "]";
};

Bây giờ hãy gọi

// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
4 và
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
5 một lần nữa:

// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
0

Bạn có thể tìm thêm chi tiết về các nguyên mẫu ở đây. Nếu bạn muốn làm nhiều kế thừa hơn, tôi khuyên bạn nên xem xét điều này.

Loạt bài viết tôi đã đề cập ở trên rất được khuyến khích đọc, chúng cũng bao gồm các chủ đề sau:highly recommended to read, they include also the following topics:

  1. Chức năng
  2. Các đối tượng
  3. Nguyên mẫu
  4. Thực thi mới về các chức năng của hàm tạo
  5. Kéo
  6. Chèn dấu chấm phẩy tự động
  7. Tính chất và phương pháp tĩnh

Lưu ý rằng "tính năng" chèn dấu chấm phẩy tự động của JavaScript [như đã đề cập trong 6.] thường rất chịu trách nhiệm gây ra các vấn đề lạ trong mã của bạn. Do đó, tôi thà coi nó là một lỗi hơn là một tính năng. that the automatic semicolon insertion "feature" of JavaScript [as mentioned in 6.] is very often responsible for causing strange issues in your code. Hence, I would rather regard it as a bug than as a feature.

Nếu bạn muốn đọc thêm, đây là một bài viết MSDN khá thú vị về các chủ đề này, một số trong số chúng được mô tả ở đó cung cấp thêm chi tiết.MSDN article about these topics, some of them described there provide even more details.

Điều thú vị để đọc [cũng bao gồm các chủ đề được đề cập ở trên] là những bài viết từ Hướng dẫn MDN JavaScript:interesting to read as well [also covering the topics mentioned above] are those articles from the MDN JavaScript Guide:

  • Giới thiệu lại cho JavaScript
  • Làm việc với các đối tượng

Nếu bạn muốn biết cách mô phỏng các tham số C#

// getters and setters - alternative syntax
var obj = { a: 7, 
            get b[] {return this.a + 1;}, 
            set c[x] {this.a = x / 2}
        };
0 [như trong
// getters and setters - alternative syntax
var obj = { a: 7, 
            get b[] {return this.a + 1;}, 
            set c[x] {this.a = x / 2}
        };
1] trong JavaScript, bạn có thể tìm thấy mã mẫu ở đây.emulate c#
// getters and setters - alternative syntax
var obj = { a: 7, 
            get b[] {return this.a + 1;}, 
            set c[x] {this.a = x / 2}
        };
0 parameters
[like in
// getters and setters - alternative syntax
var obj = { a: 7, 
            get b[] {return this.a + 1;}, 
            set c[x] {this.a = x / 2}
        };
1] in JavaScript, you can find sample code here.

Những người bạn đang làm việc với IE [không có bảng điều khiển cho JavaScript trừ khi bạn mở các công cụ nhà phát triển bằng F12 và mở tab Bảng điều khiển] có thể thấy đoạn trích sau đây hữu ích. Nó cho phép bạn sử dụng

// getters and setters - alternative syntax
var obj = { a: 7, 
            get b[] {return this.a + 1;}, 
            set c[x] {this.a = x / 2}
        };
2 như được sử dụng trong các ví dụ trên. Chỉ cần chèn nó trước hàm
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
9.working with IE [which has no console for JavaScript unless you open the developer tools using F12 and open the console tab] might find the following snippet useful. It allows you to use
// getters and setters - alternative syntax
var obj = { a: 7, 
            get b[] {return this.a + 1;}, 
            set c[x] {this.a = x / 2}
        };
2 as used in the examples above. Just insert it before the
// access object properties/functions
var podcast = new Podcast[];
podcast.title = 'The Simpsons';
console.log[podcast.toString[]];       // Title: The Simpsons
console.log[podcast.immutableProp[]];  // 123
9 function.

Để thuận tiện cho bạn, đây là mã trên trong một đoạn mã hoàn chỉnh đơn:

Notes:

  • Một số mẹo, gợi ý và đề xuất tốt về lập trình JavaScript nói chung bạn có thể tìm thấy ở đây [thực tiễn tốt nhất của JavaScript] và ở đó ['var' so với 'let']. Cũng được đề xuất là bài viết này về typecasts ngầm [ép buộc].here [JavaScript best practices] and there ['var' versus 'let']. Also recommended is this article about implicit typecasts [coercion].

  • Một cách thuận tiện để sử dụng các lớp và biên dịch chúng thành JavaScript là TypeScript. Đây là một sân chơi nơi bạn có thể tìm thấy một số ví dụ cho bạn thấy nó hoạt động như thế nào. Ngay cả khi bạn không sử dụng TypeScript tại thời điểm này, bạn có thể có một cái nhìn bởi vì bạn có thể so sánh TypeScript với kết quả JavaScript trên chế độ xem cạnh nhau. Hầu hết các ví dụ đều đơn giản, nhưng cũng có một ví dụ Raytracer mà bạn có thể thử ngay lập tức. Tôi đặc biệt khuyên bạn nên xem xét "Sử dụng các lớp", "sử dụng các ví dụ về kế thừa" và "sử dụng thuốc generic" bằng cách chọn chúng trong ComboBox - đây là những mẫu đẹp mà bạn có thể sử dụng ngay lập tức trong JavaScript. TypeScript được sử dụng với góc.TypeScript. Here is a playground where you can find some examples showing you how it works. Even if you're not using TypeScript at the moment, you can have a look because you can compare TypeScript with the JavaScript result on a side-by-side view. Most examples are simple, but there is also a Raytracer example which you can try out instantly. I recommend especially looking into the "Using Classes", "Using Inheritance" and "Using Generics" examples by selecting them in the combobox - these are nice templates you can instantly use in JavaScript. Typescript is used with Angular.

  • Để đạt được sự đóng gói của các biến cục bộ, các chức năng, vv trong JavaScript, tôi đề nghị sử dụng một mẫu như sau [JQuery sử dụng cùng một kỹ thuật]:encapsulation of local variables, functions etc in JavaScript, I suggest to use a pattern like the following [JQuery uses the same technique]:

// access static properties/functions
console.log[Podcast.FILE_EXTENSION];   // 'mp3'
Podcast.download['Astronomy cast'];    // 'Downloading Astronomy cast ...'
1

Tất nhiên, bạn có thể - và nên - đặt mã tập lệnh vào một tệp

// getters and setters - alternative syntax
var obj = { a: 7, 
            get b[] {return this.a + 1;}, 
            set c[x] {this.a = x / 2}
        };
4 riêng biệt;Điều này chỉ được viết nội tuyến để giữ ví dụ ngắn.

Các hàm tự thu hoạch [còn được gọi là iife = biểu thức chức năng được gọi ngay lập tức] được mô tả chi tiết hơn ở đây.

Bài Viết Liên Quan

Chủ Đề